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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!