Python中最后一行的矩阵计算取决于前一行的值

时间:2017-12-22 00:58:18

标签: numpy matrix

我正在初始化2个矩阵:

import numpy as np   

mtx1 = np.zeros(shape=(5,10)) #this will be the resulting matrix 
mtx2 = np.random.randn(5,10)  #random number matrix

mtx1[0] = mtx2[0]             #first row is equal to random number matrix first row

现在我想要完成 mtx1 作为之前的 mtx1 行+ mtx2 的等效行,所以结果将是等效的做:

mtx1[1] = mtx1[0] +  mtx2[1]
mtx1[2] = mtx1[1] +  mtx2[2]
mtx1[3] = mtx1[2] +  mtx2[3]
mtx1[4] = mtx1[3] +  mtx2[4]
mtx1[5] = mtx1[4] +  mtx2[5]
...
mtx1[10] = mtx1[9] +  mtx2[10]

如果我正在使用大型矩阵,那么最有效的方法是什么?

1 个答案:

答案 0 :(得分:2)

如Paul Panzer的评论所述,如果您想获得累积金额,只需使用.cumsum(axis=0),在这种情况下,这将如下所示:

#create matrix (note correction to 10 rows, 5 columns)
mtx2 = np.random.randn(10,5)

#take the cumulative sum
mtx1 = mtx2.cumsum(axis=0)

输出在这里:

#check that the output matrix is the same size
In [17]: mtx1.shape
Out[17]: (5, 10)

#show that the first row in input is same as in output
In [24]: (mtx1[0,:] == mtx2[0,:]).all()
Out[24]: True

更新(12/30/2017):

要在我们关心第i行和第(i-1)行的两个矩阵之间快速操作,您可以使用np.roll函数将所有行(列)移动任意数量。例如,假设您希望将第(i-1)行(或其某些功能输出)添加到第i行,那么我们只需执行

#initiate a simple 10 by 5 matrix of random integers between 0 and 10
mtx2 = np.random.randint(0,10,(10,5))

#add the i-1th row to the ith row (could do columns with axis=1)
out_mat = mtx2 + np.roll(mtx2,shift = 1,axis=0)

#because Numpy adds the nth row to the first row, 
#it's undesired in structured data matrixes (ie timeseries) so 
#so I annul the first row in the output

out_mat = out_mat.astype(np.float) #np.nan are floats
out_mat[0,:] = np.nan