MATLAB Answers

0

How can I sum a specified region of a matrix?

Asked by Raymond Mo on 15 Jul 2019
Latest activity Edited by Adam Danz
on 15 Jul 2019
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!

  0 Comments

Sign in to comment.

2 Answers

Answer by Adam Danz
on 15 Jul 2019
Edited by Adam Danz
on 15 Jul 2019
 Accepted Answer

"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)

  0 Comments

Sign in to comment.


Answer by KALYAN ACHARJYA on 15 Jul 2019
Edited by KALYAN ACHARJYA on 15 Jul 2019

mat=matrix_given(20:25,1:3,:);
result=sum(mat(:));
For detail read Multidimensional Arrays

  2 Comments

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.
Thanks @Steven Lord Yes, but I am using Matlab 2017a

Sign in to comment.