Matrix numpy-从矩阵索引计算值

Matrix numpy-从矩阵索引计算值,matrix,numpy,Matrix,Numpy,我需要从nxm矩阵(例如,命名a)创建一个新的(n*m)x4矩阵(例如,命名b),但出于速度原因,我不想使用嵌套循环。下面是如何使用嵌套循环执行此操作: for j in xrange(1,m+1): for i in xrange(1,n+1): index = (j-1)*n+i b[index,1] = a[i,j] b[index,2] = index b[index,3] = s1*i+s2*j+s3

我需要从
nxm
矩阵(例如,命名
a
)创建一个新的
(n*m)x4
矩阵(例如,命名
b
),但出于速度原因,我不想使用嵌套循环。下面是如何使用嵌套循环执行此操作:

for j in xrange(1,m+1):
    for i in xrange(1,n+1):
        index = (j-1)*n+i
        b[index,1] = a[i,j]
        b[index,2] = index
        b[index,3] = s1*i+s2*j+s3
        b[index,4] = s4*i+s5*j+s6

因此,问题是,如何使用从原始矩阵索引派生的值创建新矩阵?谢谢

如果你能使用numpy,你可以试试

import numpy as np
# Create an empty array
b = np.empty((np.multiply(*a.shape), 4), dtype=a.dtype)
# Get two (nxm) of indices
(irows, icols) = np.indices(a)
# Fill the b array
b[...,0] = a.flat
b[...,1] = np.arange(a.size)
b[...,2] = (s1*irows + s2*icols + s3).flat
b[...,3] = (s4*irows + s5*icols + s6).flat
对于那些有类似问题的人,一些小的更正(不能作为评论发布:/):

import numpy as np
# Create an empty array
b = np.empty((a.size, 4), dtype=a.dtype)
# Get two (nxm) of indices (starting from 1)
(irows, icols) = np.indices(a.shape) + 1
# Fill the b array
b[...,0] = a.flat
b[...,1] = np.arange(a.size) + 1 
b[...,2] = (s1*irows + s2*icols + s3).flat
b[...,3] = (s4*irows + s5*icols + s6).flat

我不懂索引。假设
m=5
n=4
,则第一次迭代的
index
值为
5
。循环将设置
b[5,:]
的值,保持
b[0:4,:]
不变。这就是我的意图吗?你完全正确,我非常抱歉:我“在飞行中”编写了代码,距离上次编写代码已经有一段时间了:$。不过我希望你能理解这个问题的意思,我只是说我需要用一种缓慢的嵌套循环方法扫描整个矩阵。谢谢!我自己也找到了类似的解决方案,但这更好