How can I sum only few values in a diagonal matrix?

5 ビュー (過去 30 日間)
Rida
Rida 2014 年 4 月 14 日
回答済み: Walter Roberson 2018 年 3 月 26 日
if I have a diagonal matrix, and I use sum(diag(A)) , it gives me the sum of entire diagonal, but I only want the sum of lets say 1st three values in the diagonal? How can I add them?
Thank you!!

採用された回答

Mischa Kim
Mischa Kim 2014 年 4 月 14 日
Rida, use
sum(diag(A(1:3,1:3)))
  1 件のコメント
mohammed abdul wadood
mohammed abdul wadood 2018 年 3 月 26 日
a tired it with my data, it's work perfectly, thanks Mischa.

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

その他の回答 (2 件)

Alberto
Alberto 2014 年 4 月 14 日
Sum=0;
for k=1:3 % will sum 3 first diagonal elements Sum=Sum+A(k,k);
end
You can change the range k=1:3 with an array with the index of elements u want to sum.
  1 件のコメント
mohammed abdul wadood
mohammed abdul wadood 2018 年 3 月 26 日
it's work to, thanks Alberto

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


Walter Roberson
Walter Roberson 2018 年 3 月 26 日
Without a loop:
r = size(A, 1);
sum(A([1, r+1, 2*(r+1)]))

カテゴリ

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