Multiply the same Matrix by N times

1

I am trying to multiply a matrix using numpy by itself N times, this is my current code

import numpy as np
fil1=3
col1=2

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

The error I have is that in mat3[r,c]=mat1[r,c]*mat1[r,c] the result does not multiply well, how could I implement it for N times?

#Example Mat1^3 = 
[ 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 ]

[ 30  36  42       [ 1  2  3        [ ?  ?  ? 
  66  81  96    *    4  5  6    =     ?  ?  ?
  102 126 150 ]      7  8  9 ]        ?  ?  ?]
    
asked by Diego 25.09.2018 в 08:27
source

1 answer

1

To multiply a matrix by itself n times, simply:

# Declarar matriz
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Elevar a la n potencia donde n=3
B = np.linalg.matrix_power(A,3)

Matrix multiplication can be done using the np.dot command, so the same result can be achieved within an iteration:

# Copiar A
B = A.copy()

# Para elevar a la n evalúese un rango igual a n - 1
for i in range(2):
    B = np.dot(B,A)

And even simpler:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A = np.matrix(A)
B = A**3

Although, in case you want to do it step by step, and resorting to a cycle (iterative method):

import numpy as np

# Ejemplo de matrices cuadradas (donde n = m):
a = np.array([[1,2],[3,4]])
b = np.array([[1,2],[3,4]])

# Función para llevar a cabo la multiplicación de dos matrices:
def matMul(a,b):
    m_a = a.shape[0]
    n_a = a.shape[1]
    n_b = b.shape[1]
    c_ = np.array([[0,0],[0,0]])
    for i in range(m_a):
        for j in range(n_b):
            for k in range(n_a):
                c_[i,j] += a[i,k]*b[k,j]
    return c_


# Elevar una matriz 'a' a la 'n' potencia:
def matExp(a,n):
    n -= 1
    c_ = a.copy()
    for i in range(n):
        c_ = matMul(c_,a)
    return c_

Now it's enough to execute the function:

matExp(a,3)
    
answered by 25.09.2018 в 13:27