Sum each page of a 3D matrix and append sums as rows of new 2D matrix

2 ビュー (過去 30 日間)
May_the_degrees_of_freedom_be_with_you
編集済み: Matt J 2020 年 9 月 13 日
I cannot for the life of me figure out why this for loop is overwriting the first row of my output variable (D). I have spent a few hours now reading through Matlab forums/documentation, and it appears that I've written this correctly but it's still overwriting.
I have a 2D matrix (A), a second 2D matrix (B), and I've concatenated these to make a 3D matrix (C) where Page 1 = A and Page 2 = B. I want to sum each page of C and name D such that each row of D is the sum of each column of each page in C. So, the final output for D should be [15 15 15; 25 25 25]. I believe the output is [0 0 0 ; 25 25 25] because Matlab is overwriting the first iteration of the for loop and pasting only the results of the second (and final) iteration.
Example code:
A = [5 5 5; 10 10 10]
B = [15 15 15; 10 10 10]
C = cat(3,A,B)
D = zeros(2,3)
for i = 2
D(i,:) = sum(C(:,:,i),1)
end
Where am I going wrong?
Thank you in advance.
  1 件のコメント
May_the_degrees_of_freedom_be_with_you
Finally solved it! Copying my answer here in case anyone else is having a similar problem.
Thank you to "M" from this thread (https://www.mathworks.com/matlabcentral/answers/376632-matrix-filling-with-for-loop)--I got this to work from trying an alternate form of the "i" parameter that "M" used.
A = [5 5 5; 10 10 10]
B = [15 15 15; 10 10 10]
C = cat(3,A,B)
D = zeros(2,3)
for i = 1:2
D(i,:) = sum(C(:,:,i),1)
end

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

採用された回答

Matt J
Matt J 2020 年 9 月 13 日
編集済み: Matt J 2020 年 9 月 13 日
D=permute(sum(C,1),[3,2,1])

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by