Week 5: Matrix with list

Hi
please explain why it it considering (n-1)iteration in for loop

def matrix (A,n):

output=[i[:] for i in A]        

temp=[i[:]for i in A]            

for i in range (n-1): 

   output [0][0]= A[0][0]* temp [0][0]+ A[0][1]* temp [1][0]

    output [0][1]= A[0][0]* temp [0][1]+ A[0][1]* temp [1][1]

    output [1][0]= A[1][0]* temp [0][0]+ A[1][1]* temp [1][0]

    output [1][1]= A[1][0]* temp [0][1]+ A[1][1]* temp [1][1]

    temp = [i[:] for i in output]

return output

print (matrix (A,1))

if we don’t use (n-1) later
When we asign n=1 , it goes into loop
we get output as A*A , because of i initially takes value 0,
So loop runs for 1 times
But actually for n=1, we have to get A power 1, which is A itself
Now if use (n -1) … loop doesnot run for n = 1

1 Like

The problem is to find nth power of A. So A has to be multiplied with (n-1) power of A. Hence (n-1) iterations.
If we do n iterations, then A will be multiplied to n to the power of A which will result in (n+1) power of A.

You can verify this with n=1 and you will understand.