簡體   English   中英

將矩陣提高到n次方

[英]Raising a matrix to the nth power

我正在嘗試將矩陣本身相乘n次

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)

我如何通過將同一矩陣乘以n來實現它?

#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 ]

您可以使用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))

使用for循環的非遞歸方式:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM