Sum of each row?

3 ビュー (過去 30 日間)
Serra Aksoy
Serra Aksoy 2020 年 2 月 8 日
コメント済み: Serra Aksoy 2020 年 2 月 9 日
Hi,
I have a set
A=ones(2,3,4);
Here,
val(:,:,1) =
1 1 1
1 1 1
val(:,:,2) =
1 1 1
1 1 1
....
I want to create a matrix whose elements are the sum of each row of A.
The sum of the first row of val(:,:,1) should be a11 in A.
The sum of the second row of val(:,:,1) should be a12 in A.
The sum of the first row of val(:,:,2) should be a21 in A.
The sum of the second row of val(:,:,2) should be a22 in A....
How can i form this 4x2 matrix ?
Thanks in advance.

採用された回答

Adam Danz
Adam Danz 2020 年 2 月 8 日
編集済み: Adam Danz 2020 年 2 月 8 日
A = reshape(1:24,2,3,4); % input: [n x m x k] array
val = squeeze(sum(A,2)).'; % output: [k x n] matrix
  3 件のコメント
Stephen23
Stephen23 2020 年 2 月 9 日
編集済み: Stephen23 2020 年 2 月 9 日
Using squeeze is very fragile because it's output changes completely when some dimension's size happens to be one. The simple and robust alternative is to use permute (which also requires fewer operations than the above answer):
>> permute(sum(A,2),[3,1,2])
ans =
9 12
27 30
45 48
63 66
Serra Aksoy
Serra Aksoy 2020 年 2 月 9 日
For my problem, both of the codes solved it well. Thank you for your clear explanation.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by