没有numpy的矩阵求幂

时间:2020-11-04 12:01:38

标签: python matrix

我需要编写一个执行矩阵通常幂运算的函数

  measure = countrows(FILTER (
        ADDCOLUMNS (
            VALUES ( 'Rating Change'[CustomerNumber] ),
            "maxRating",
                CALCULATE (
                    MAX ( 'Rating CHange'[Rating] ),
                    FILTER (
                        ALL ( 'Rating Change'[RatingDate] ),
                        VAR _x =
                            CALCULATE (
                                MAX ( 'Rating Change'[RatingDate] ),
                                YEAR ( 'Rating Change'[RatingDate] ) = YEAR ( TODAY () )
                            )
                        RETURN
                            'Rating Change'[RatingDate] = _x
                    )
                ),
            "maxRatingLY",
                CALCULATE (
                    MAX ( 'Rating CHange'[Rating] ),
                    FILTER (
                        ALL ( 'Rating Change'[RatingDate] ),
                        VAR _x =
                            CALCULATE (
                                MAX ( 'Rating Change'[RatingDate] ),
                                YEAR ( 'Rating Change'[RatingDate] )
                                    = YEAR ( TODAY () ) - 1
                            )
                        RETURN
                            'Rating Change'[RatingDate] = _x
                    )
                )
        ),
        [maxRatingLY] - [maxRating] > 3
    )
    )

但是由于某种原因,它给出的答案与def matrix_power(a, power): rows, columns = len(a), len(a[0]) result = np.zeros((rows, columns)) b = a for step in range(1, power): for i in range(0, rows): for j in range(0, columns): for m in range(0, rows): result[i][j] += a[i][m] * b[m][j] a = result return result matrix_power(matrix, 3) 不同,这可能是什么问题?

2 个答案:

答案 0 :(得分:1)

看到这个:

>>> import numpy as np
>>> result = np.zeros((3, 3))
>>> result
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
>>> a = result
>>> result[1][0] += 42
>>> result
array([[ 0.,  0.,  0.],
       [42.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> a
array([[ 0.,  0.,  0.],
       [42.,  0.,  0.],
       [ 0.,  0.,  0.]])

代码中的问题是您没有将result复制到a,并且稍后在循环中更改result时,同时更改了a

要复制,请用以下内容替换您的作业:

a = result.copy()

答案 1 :(得分:1)

def matrix_power(a, power):
    rows, columns = len(a), len(a[0])
    result = np.zeros((rows, columns))
    b = a
    for step in range(1, power):
        result = np.zeros((rows, columns)) # reset result to all zeroes matrix here
        for i in range(0, rows):
            for j in range(0, columns):
                for m in range(0, rows):
                    result[i][j] += a[i][m] * b[m][j]
        
        a = result
    for val in result:
        print(val)
    return result