numpy - 从矩阵索引计算值

时间:2012-08-09 06:55:39

标签: matrix numpy

我需要从(n*m) x 4矩阵(例如名为b)创建一个新的n x m矩阵(例如名为a),但我不想使用嵌套循环出于速度原因。在这里我将如何使用嵌套循环:

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

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

2 个答案:

答案 0 :(得分:3)

如果你可以使用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

答案 1 :(得分:0)

对于那些有类似问题的人,可以进行一些小的更正(不能发表评论:/):

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
相关问题