-1

for eg if i have a matrix

 4     5     9     8     3     8
 3     2     4    10     1     3
 1     9     9     6     7     7
 2     1     7     4     6     7
 2     6     3     5     4     2
 7     2     2     9     3     4

How do I calculate the sum of the diagonal of the element 10 if I have its row and column indices?

So the output should be 9 + 10 + 7 + 7.

Thanks!

TYL
  • 1,577
  • 20
  • 33
  • just add and subtract the row and column indices by 1 at the same time and add the element at that position if it exists. for example, if the index of 10 is (2,4) then sum of diagonal will be (2,4) + (1,3) + (3,5) + (4,6) = 10 + 9 + 7 + 7 – Swastik Padhi Oct 22 '15 at 03:11

2 Answers2

4
column = 4;
row = 2;
output = sum(diag(A, column - row));
gregswiss
  • 1,456
  • 9
  • 20
0

Here you go:

>> x = [4,5,9,8,3 ,8
3,2,4,10,1, 3
1,9,9,6,7 ,7
2,1,7,4,6 ,7
2,6,3,5,4 ,2
7,2,2,9,3 ,4]
x =

    4    5    9    8    3    8
    3    2    4   10    1    3
    1    9    9    6    7    7
    2    1    7    4    6    7
    2    6    3    5    4    2
    7    2    2    9    3    4

>> xsum = sum(diag(x,4-2));
>> xsum
xsum =  33

parameterize the indices in case you need to use it more than once.

ForeverLearner
  • 1,901
  • 2
  • 28
  • 51