how to traverse a multidimensional array

12 views (last 30 days)
zhang
zhang on 20 Feb 2014
Answered: David Young on 20 Feb 2014
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

Answers (2)

Sean de Wolski
Sean de Wolski on 20 Feb 2014
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

David Young
David Young on 20 Feb 2014
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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!