Search code examples
matlabmatrixdiagonal

To Get Diagonals of a Matrix in Matlab?


I want to get diagonals from a matrix in Matlab. For example, given the following matrix

M = [1  1   4   5   4
     2  5   1   2   2
     4  1   2   1   3
     1  3   1   1   1
     1  2   3   3   1]

I want to get a list of vectors which make the upper diagonals: {[1 1 1 1], [4 2 3], [5 2] [4]}.

One attempt

I want to replace if-clauses by a while-loop in Matlab

     if (i==j)
        A(t+1,i) = M(i,j)
     end
     if (i==j+1) 
        A(t+1,i) = M(i,j)
     end
     ...
     if (i==j+N) 
        A(t+1,i) = M(i,j)
     end

To store all diagonals of the matrix

t = 0;
while (t < 5)   % if-clauses replaced here by this
   for i=1:5
      for j=i:5
          if (i == j+t)
             trend(t+1,i) = M(i,j); 
          end
      end
   end
t = t + 1;
end

The idea is to store elements into the matrix trend with the condition i == j+t that is a condition I find holds for the diagonals of the upper triangle. The if-clauses are replaced by false pseudocode, which tries to go through the upper triangle of the matrix, but false because no "1" vector found in trend


How can you get diagonals from a matrix in Matlab?


Solution

  • If I understood correctly, you want to use the spdiags function to extract the upper off-diagonals. Example:

    N = 5;
    M = magic(N)
    D = spdiags(M, 1:N-1)
    DD = arrayfun(@(i) D(i+1:end,i).', 1:N-1, 'Uniform',false)
    celldisp(DD)
    

    The result:

    M =
        17    24     1     8    15
        23     5     7    14    16
         4     6    13    20    22
        10    12    19    21     3
        11    18    25     2     9
    
    D =
         0     0     0     0
        24     0     0     0
         7     1     0     0
        20    14     8     0
         3    22    16    15
    
    DD = 
        [1x4 double]    [1x3 double]    [1x2 double]    [15]
    DD{1} =
        24     7    20     3
    DD{2} =
         1    14    22
    DD{3} =
         8    16
    DD{4} =
        15