Diego
Diego

Reputation: 77

Raising a matrix to the nth power

I'm trying to multiply a matrix by itself, n times

import numpy as np
fil1=3
col1=2

mat1 = random.random((fil1,col1))
mat3 = np.zeros((fil1,col1))
pot = 3
print('Matriz A:\n',mat1) 
for r in range(0,fil1):
    for c in range (0,col1):
        mat3[r,c]=mat1[r,c]*mat1[r,c]
print('Pot:\n',mat3)

How could I implement it by multiplying the same matrix by n times ??

#Example Mat1^2 = 
[ 1  2  3     [ 1  2  3       [ 1  2  3       [ 30  36  42 
  4  5  6   =   4  5  6    *    4  5  6     =   66  81  96
  7  8  9 ]     7  8  9 ]       7  8  9 ]       102 126 150 ]

Upvotes: 1

Views: 3095

Answers (1)

Ishpreet
Ishpreet

Reputation: 5880

You can create your own recursive function using numpy.matmul:

import numpy as np

a = [[1,2,3], [4,5,6], [7,8,9]];

def matrixMul(a, n):
    if(n <= 1):
        return a
    else:
        return np.matmul(matrixMul(a, n-1), a)

print(matrixMul(a, 4))

Non recursive way using for-loop:

import numpy as np
a = [[1,2,3], [4,5,6], [7,8,9]];

def matrixMul(a, n):
    if(n == 1):
        return a
    else:
            tempArr = a;
            for i in range(1, n-1):
                tempArr = np.matmul(a, tempArr)
            return tempArr

print(matrixMul(a, 4))

Upvotes: 1

Related Questions