Search code examples
matlabmatrixdiagonal

Replace the diagonal of matrix


I am interesting to replace the diagonal of matrix D to 1,2,3,4. This is matrix D:

A=[1,2,3,4,2,3,4,5; 3,4,5,6,4,5,6,7];
D=[A;A];
D=[D D]; % size of matrix [4x16] %

Solution

  • To set the main diagonal to integers starting a 1 and incrementing by 1:

    D(eye(4)==1) = 1:4
    

    Or to generalize it:

    n = min(size(D));
    D(eye(n)==1) = 1:n;
    

    note here that the ==1 is to convert the output of eye(n), the identity matrix, to type logical.

    EDIT:

    This is just a guess at what you mean by all the diagonals but here goes:

    n = size(D,1);
    m = size(D,2);
    I = repmat(eye(min([n,m])), ceil(n/m), ceil(m/n));
    I = I(1:n, 1:m)==1
    d = repmat(1:min([n,m]), 1, max([ceil(n/m), ceil(m/n)]));
    d = d(1:max(m,n));
    D(I) = d