Matlab exercise: how to sum diagonals elements?

194 Views Asked by At

I'm trying to solve this exercise in MATLAB: Given a square matrix A, define the vector having for components, for every diagonal of A, the sum of the diagonal elements.

Example: $$ A = \left(\begin{matrix} -1 & 2 & 0\\ 0 & 5 & 1\\ -2 & 0 & 1\end{matrix}\right) $$

then $$ v = \left[\begin{matrix} -2 & 0 & 5 & 3 & 0 \end{matrix}\right] $$

Could anyone help me to do this in MATLAB in the simplest wai it is possible?

Edit: A is a generic n - square matrix.

2

There are 2 best solutions below

1
On BEST ANSWER

I've never written MATLAB before, so I apologize if this either misses a language-specific trick such as @GuusB's or has some slight syntax errors. But regardless of language, the trick with these problems is to make a vector full of zeros, then decide how to modify it based on each element of the matrix, so each such element is considered only once. To wit:

n = size(A)(1);    
v = zeros(2*n-1);    
for i=1:n    
    for j=1:n
        k = n-i+j;    
        v(k) = v(k)+A(i, j);    
    end    
end
0
On

diag(A,i) gives the $i$'th diagonal of $A$, where $i=0$ represents the main diagonal. So your vector elements will be sum(diag(A,i)) for i = -(n-1):n-1.