How can I sum a specified region of a matrix?

42 ビュー (過去 30 日間)
Raymond Mo
Raymond Mo 2019 年 7 月 15 日
編集済み: Adam Danz 2019 年 7 月 15 日
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!

採用された回答

Adam Danz
Adam Danz 2019 年 7 月 15 日
編集済み: Adam Danz 2019 年 7 月 15 日
"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)

その他の回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 15 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 15 日
mat=matrix_given(20:25,1:3,:);
result=sum(mat(:));
For detail read Multidimensional Arrays
  2 件のコメント
Steven Lord
Steven Lord 2019 年 7 月 15 日
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 2019 年 7 月 15 日
Thanks @Steven Lord Yes, but I am using Matlab 2017a

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by