フィルターのクリア

How to Sum matrix diagonals

48 ビュー (過去 30 日間)
Krish Desai
Krish Desai 2015 年 9 月 27 日
コメント済み: Tia Miller 2018 年 10 月 15 日
If I have the following matrix
a = [1 2 3; 4 5 6; 7 8 10
a =
1 2 3
4 5 6
7 8 10
How do I sum the diagonal of 7,5,3? I know that to sum 1,5,10 I use
sum(diag(a))
But when I try
sum(diag(a,2))
The answer is 3. Is there a built in function that calculates the sum, or do I have to make a while loop?
  1 件のコメント
Tia Miller
Tia Miller 2018 年 10 月 15 日
sum(diag(a,2)) is summing the diagonal 2 away from the main diag, which has one entry, 3.
sum(diag(flip(a))) will sum 3, 5, 7, or the main diag after the matrix has been flipped

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2015 年 9 月 27 日
編集済み: Andrei Bobrov 2015 年 9 月 27 日
sum(diag(a(:,end:-1:1)));
or summing all diagonals:
sum(spdiags(rot90(a)));

その他の回答 (2 件)

John D'Errico
John D'Errico 2015 年 9 月 27 日
sum(diag(flip(A)))
should work.

Ahmed Diaa
Ahmed Diaa 2018 年 5 月 5 日
x=sum(diag(E));% calculating the normal diagonal
y=sum(diag(flip(E)));% calculating the inverse diagonal
z=[];% subtracting the common element
s=y+x-z ;% the sum

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by