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

29 views (last 30 days)
Rida on 14 Apr 2014
Answered: Walter Roberson on 26 Mar 2018
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!!

Accepted Answer

Mischa Kim
Mischa Kim on 14 Apr 2014
Rida, use
  1 Comment
mohammed abdul wadood
mohammed abdul wadood on 26 Mar 2018
a tired it with my data, it's work perfectly, thanks Mischa.

Sign in to comment.

More Answers (2)

Alberto on 14 Apr 2014
for k=1:3 % will sum 3 first diagonal elements Sum=Sum+A(k,k);
You can change the range k=1:3 with an array with the index of elements u want to sum.

Walter Roberson
Walter Roberson on 26 Mar 2018
Without a loop:
r = size(A, 1);
sum(A([1, r+1, 2*(r+1)]))


Community Treasure Hunt

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

Start Hunting!