How can I sum a specified region of a matrix?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Raymond Mo
am 15 Jul. 2019
Bearbeitet: Adam Danz
am 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 Kommentare
Akzeptierte Antwort
Adam Danz
am 15 Jul. 2019
Bearbeitet: Adam Danz
am 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)
0 Kommentare
Weitere Antworten (1)
KALYAN ACHARJYA
am 15 Jul. 2019
Bearbeitet: KALYAN ACHARJYA
am 15 Jul. 2019
mat=matrix_given(20:25,1:3,:);
result=sum(mat(:));
For detail read Multidimensional Arrays
2 Kommentare
Steven Lord
am 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.
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!