Reputation: 2299
Consider an N
-D array in Matlab composed of (nbins)^(N-2)
sub-matrices of size nbins x nbins
.
For example,
clear
rng default
N=5;
nbins=3;
A=randn(nbins,nbins,nbins,nbins,nbins);
Let M
be an integer less or equal than N
. I want to write a generic code that gives me an M
-D array, B
, obtained by summing A
along the dimensions M+1,M+2,...,N
.
For example, continuing above,
M=4;
%B is nbins x nbins x nbins x nbins with
B=A(:,:,:,:,1)+A(:,:,:,:,2)+A(:,:,:,:,3);
M=3;
%B is nbins x nbins x nbins with
B_temp=A(:,:,:,:,1)+A(:,:,:,:,2)+A(:,:,:,:,3);
B=B_temp(:,:,:,1)+B_temp(:,:,:,2)+B_temp(:,:,:,3);
M=2
%B is nbins x nbins with
B_temp1=A(:,:,:,:,1)+A(:,:,:,:,2)+A(:,:,:,:,3);
B_temp2=B_temp(:,:,:,1)+B_temp(:,:,:,2)+B_temp(:,:,:,3);
B= B_temp2(:,:,1)+B_temp2(:,:,2)+B_temp2(:,:,3);
Upvotes: 1
Views: 104
Reputation: 60799
Since R2018b, the function sum
can sum along multiple dimensions simultaneously. Thus, you can sum over the dimensions M+1
through N
by
B = sum(A,M+1:N);
For older versions of MATLAB, you could sum over each dimension in turn:
B = A
for ii=M+1:N
B = sum(B,ii);
end
However, Luis’ answer will be more performant in the pre-R2018b case because it avoids the intermediate storage, and does just one pass over the array (at least if all dimensions to be summed over are contiguous, for non-contiguous dimensions you should time these two approaches to see which is faster).
Upvotes: 2
Reputation: 112769
Since you want to sum along several contiguous dimensions, it's very easy to collapse those dimensions into one using reshape
, and then sum over that dimension. This approach applies sum
over one dimension only, and thus works even in versions before R2018b, which don't support summing over multiple dimensions at once.
sz = size(A);
B = sum(reshape(A, [sz(1:M) prod(sz(M+1:end))]), M+1);
(If the dimensions to sum over were not contiguous, permute
would be needed before reshape
to make them contiguous, and the code might be slightly slower.)
Upvotes: 2