how to traverse a multidimensional array
10 次查看(过去 30 天)
显示 更早的评论
Given a multidimensional array A = MxMxMx...xM, where ndims(A)=n. My problem can be described by the following pseudo-code:
sum(A(i, :, :, :, ..., :)) i = 1, ... M
sum(A(:, i, :, :, ..., :)) i = 1, ... M
...
sum(A(:, :, :, :, ..., i)) i = 1, ... M
I really don't know how to do this. Can anyone help me?
Thanks
0 个评论
回答(2 个)
Sean de Wolski
2014-2-20
A trick here is to use the string ':' as an element in a cell array that you can pass in as a comma-separated list.
Simple example:
c = {':',3} % all elements, third column
x = magic(5)
x(c{:})
(This is an advanced manuever)
% Build a random rand-d matrix
k = randi(5)+3;
sz = randperm(8,k);
Z = rand(sz);
nd = numel(sz);
% Some function
do_something_with = @size; % size is just an example
for ii = 1:numel(sz)
% loop over dimensions
% build cell array with only iith dimension having values, everything else ':'
traverse = repmat({':'},1,nd);
for kk = 1:sz(ii)
% loop over the iith dimension
traverse{ii} = kk;
do_something_with(Z(traverse{:}))
end
end
0 个评论
David Young
2014-2-20
Maybe I'm oversimplifying the problem, but if I've understood the pseudocode this should work:
n = ndims(A);
s = cell(1, n);
for d = 1:n
s{d} = squeeze(sum(A, d));
end
Afterwards, s{d} has an n-1 dimensional array which is A summed over the d'th dimension.
Sean de Wolski's solution is more general if you want something other than the sum, of course.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!