How to find the sum of all column vectors of the elements on the kth diagonal of a square matrix in Matlab ?

3 ビュー (過去 30 日間)
Hello, sir/madam. I need your help to find a solution to the following case.
n = 3;
A = magic(n)
B = diag(diag(A,0));
C = sum(sum(B))
D = triu(A) + tril(A) + diag(B(B>0)+C) - (2*diag(diag(A,0)))
A =
8 1 6
3 5 7
4 9 2
C =
15
D =
23 1 6
3 20 7
4 9 17
As can be seen, I found the main diagonal elements and added their sum to each column vector element, as shown in D. But, I can’t do that for following column vector elements (for any n value):
B1 =
0 1 0
0 0 7
0 0 0
B1 = sum(sum(B1)) = 8
B2 =
0 0 6
0 0 0
0 0 0
B2 = sum(sum(B2)) = 6
B3 =
0 0 0
3 0 0
0 9 0
B3 = sum(sum(B3)) = 12
B4 =
0 0 0
0 0 0
4 0 0
B4 = sum(sum(B4)) = 4
Can anyone help me to write a code that can do that so that I can obtain the following output ?
D =
23 9 6
15 20 15
4 21 17
Thank you!

採用された回答

Massimo Zanetti
Massimo Zanetti 2016 年 10 月 6 日
編集済み: Massimo Zanetti 2016 年 10 月 6 日
Here it is the code that does the work. Inspect the function diag and partial results at each iteration.
n = size(A,1);
for k = -n+1:n-1
%get kth diagonal sum
v = sum(diag(A,k));
%add the sum to the kth diagonal of a
A = A + diag(v*ones(n-abs(k),1),k)
end
  2 件のコメント
Gobert
Gobert 2016 年 10 月 6 日
編集済み: Gobert 2016 年 10 月 6 日
Thank you very much, Massimo Zanetti!
Massimo Zanetti
Massimo Zanetti 2016 年 10 月 6 日
You are welcome :) Vote my answer if you liked!

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

その他の回答 (1 件)

KSSV
KSSV 2016 年 10 月 6 日
A = [ 8 1 6
3 5 7
4 9 2];
C = 15 ;
C = C*eye(size(A)) ;
iwant = A+C
  2 件のコメント
Gobert
Gobert 2016 年 10 月 6 日
Thanks,Siva, but it does not produce the following:
D =
23 9 6
15 20 15
4 21 17
That's a shortcut to produce the following (I had done).
D =
23 1 6
3 20 7
4 9 17
KSSV
KSSV 2016 年 10 月 6 日
Ohk..what I have done only adds to diagonal elements..

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

カテゴリ

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