2012-08-09 110 views
1

我需要從n x m矩陣(例如名爲a)創建一個新的(n*m) x 4矩陣(例如名爲b),但我不想使用嵌套循環出於速度原因。在這裏,我將如何嵌套循環做到這一點:numpy - 從矩陣索引計算值

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 

的問題,因此,如何建立與原來的矩陣索引中得出的值一個新的矩陣?由於

+0

我不不瞭解索引。說'm = 5'和'n = 4',那麼第一次迭代中'index'的值就是'5'。你的循環會設置'b [5,:]'的值,而不會改變'b [0:4,:]'。這是意圖嗎? – mtrw 2012-08-09 07:54:29

+0

你是完全正確的,我完全對不起:我寫了代碼「在飛行中」,自從我上次寫了代碼:$以來已經有一段時間了。不過,我希望你能明白這個問題的含義,我僅僅意味着我需要用慢嵌套循環方法掃描整個矩陣。 – andreaconsole 2012-08-09 08:12:16

回答

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 
+0

謝謝!我自己找到了一個類似的解決方案,但這更好 – andreaconsole 2012-08-15 13:08:12

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