Summing the diagonal of a matrix "the other way"?

18 ビュー (過去 30 日間)
Emanuele Joy
Emanuele Joy 2018 年 6 月 8 日
編集済み: Birdman 2018 年 6 月 8 日
I don't know if I'm wording it correctly, but I'm trying to sum the diagonal of a matrix the other "direction" than the diag(A) function. For example, I have a matrix:
A =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
If I use diag(A), it'd give me 1 + 6 + 11 + 16, but I'm looking for:
1
2 + 5
3 + 6 + 9
4 + 7 + 10 + 13
And put all the sums in a 1xn array, much like a Fibonacci sequence. Is there a function that can do this, or can diag(A) be altered in someway?
  1 件のコメント
Aquatris
Aquatris 2018 年 6 月 8 日
編集済み: Aquatris 2018 年 6 月 8 日
Try this solution ; https://www.mathworks.com/matlabcentral/answers/294766-most-efficient-way-to-sum-anti-diagonal-elements

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

採用された回答

Birdman
Birdman 2018 年 6 月 8 日
編集済み: Birdman 2018 年 6 月 8 日
This can be done as follows:
res=[sum(diag(fliplr(A),3)) sum(diag(fliplr(A),2)) sum(diag(fliplr(A),1)) sum(diag(fliplr(A)))]
or it can be done in a for loop:
for i=1:size(A,1)
res(i)=sum(diag(fliplr(A),size(A,1)-i))
end

その他の回答 (0 件)

カテゴリ

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