How can I sum a specified region of a matrix?
42 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Adam Danz
il 15 Lug 2019
Modificato: Adam Danz
il 15 Lug 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 Commenti
Più risposte (1)
KALYAN ACHARJYA
il 15 Lug 2019
Modificato: KALYAN ACHARJYA
il 15 Lug 2019
mat=matrix_given(20:25,1:3,:);
result=sum(mat(:));
For detail read Multidimensional Arrays
2 Commenti
Steven Lord
il 15 Lug 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.
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!