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

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)))

추가 답변 (2개)

Alberto
Alberto 2014년 4월 14일

0 개 추천

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.
Walter Roberson
Walter Roberson 2018년 3월 26일
Without a loop:
r = size(A, 1);
sum(A([1, r+1, 2*(r+1)]))

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

질문:

2014년 4월 14일

답변:

2018년 3월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by