How can I sum a specified region of a matrix?

42 views (last 30 days)
So I have a matrix that's 30 x 5 x 2048 and I want to sum a certain region of it along the 3rd dimension. So for example I want to sum together in the x dimension (20 to 25), and in the y direction (1 to 3) all of the z direction values into one array that is 1 by 2048. Currently I'm doing it with nested for loops which is taking too long to run and I want to move over to the sum method instead. Yet I'm not sure how to specify it for a 3d matrix
Here's what I have currently
counts = zeros(1,2048);
for r = startx:(startx+sizex-1)
for c = starty:(starty+sizey-1)
counts = counts + squeeze(data.SI(c,r,:));
end
end
Thanks in advance!

Accepted Answer

Adam Danz
Adam Danz on 15 Jul 2019
Edited: Adam Danz on 15 Jul 2019
"I want to sum together in the x dimension (20 to 25), and in the y direction (1 to 3) all of the z direction values into one array that is 1 by 2048"
m = randi(1000,30,5,2048); % fake data
v = squeeze(sum(m(20:25,1:3,:),[1,2])) % 2048x1 vector sum
v(n) is the sum of m(20:25, 1:3, n)

More Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 15 Jul 2019
Edited: KALYAN ACHARJYA on 15 Jul 2019
mat=matrix_given(20:25,1:3,:);
result=sum(mat(:));
For detail read Multidimensional Arrays
  2 Comments
Steven Lord
Steven Lord on 15 Jul 2019
This sums all the elements in that section of the matrix. If that was your goal, if you're using release R2018b or later you could specify 'all' in the sum call.
A = rand(50, 5, 1048);
result = sum(A(20:25, 1:3, :), 'all');
But my interpretation of the question matches Adam Danz's, where you don't want to sum over all three dimensions of the subset of A but just the first and second. Again, as of R2018b you can specify a vector of dimensions to sum.
KALYAN ACHARJYA
KALYAN ACHARJYA on 15 Jul 2019
Thanks @Steven Lord Yes, but I am using Matlab 2017a

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!