2014-02-20 150 views
0

給定一個多維數組A = MxMxMx ... xM,其中ndims(A)= n。我的問題可以用下面的僞代碼來描述:如何遍歷多維數組

tmp = A(i, :, :, :, ..., :) 
sum(tmp(:)) i = 1, ... M 
tmp = A(:, i, :, :, ..., :) 
sum(tmp(:)) i = 1, ... M 
    ... 
tmp = A(:, :, :, :, ..., i) 
sum(tmp(:)) i = 1, ... M 

讓我用一個例子來說明它。

C = 1:81; 
A = reshape(C, 3, 3, 3, 3); 
result = zeros(3, 4); 
for i = 1 : 3 
    tmp = A(i, :, :, :); 
    result(1, i) = sum(tmp(:)); 
end 
for i = 1 : 3 
    tmp = A(:, i, :, :); 
    result(2, i) = sum(tmp(:)); 
end 
for i = 1 : 3 
    tmp = A(:, :, i, :); 
    result(3, i) = sum(tmp(:)); 
end 
for i = 1 : 3 
    tmp = A(:, :, :, i); 
    result(4, i) = sum(tmp(:)); 
end 

我真的不知道該怎麼做。誰能幫我?

感謝

+2

這是不容易理解。你能用一個3x3x3矩陣來說明嗎? –

+0

@ RobertP.我補充了一個例子。感謝您的建議。 – Fihop

回答

2

如何

sumsAlongDims = zeros(M, n); % M sums per dim 
for dim = 1:n 
    tmp = permute(A, [dim 1:(dim-1) (dim+1):n]); % bring dim to front 
    tmp = reshape(tmp, M, []); % make it 2D 
    sumsAlongDims(:, dim) = sum(tmp, 2); % gives to the m sums along each coordinate of dimension "dim" at once 
end