How to Sum matrix diagonals
156 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Krish Desai
il 27 Set 2015
Commentato: Tia Miller
il 15 Ott 2018
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 Commento
Tia Miller
il 15 Ott 2018
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
Risposta accettata
Andrei Bobrov
il 27 Set 2015
Modificato: Andrei Bobrov
il 27 Set 2015
sum(diag(a(:,end:-1:1)));
or summing all diagonals:
sum(spdiags(rot90(a)));
0 Commenti
Più risposte (2)
Ahmed Diaa
il 5 Mag 2018
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!