matlabmatrixdiagonallogical-or

Populate Lower Sub-diagonal of a Square Matrix with Specified Value MATLAB


I have an N by N matrix W_res,DLR of all zeros. I would like to populate just the lower sub diagonal elements with the scalar value r. For example, if N=4, the matrix should look like: enter image description here I thought this would work:

r = 0.5;
W_res,DLR = zeros(N,N);
W_res,DLR(logical(diag(ones(1,N-1),-1))) = r*ones(1,N-1)

but this is not the case. W_res,DLR is a matrix of all NaNs. Where am I going wrong?


Solution

  • Like this?

    >> N = 4;
    >> r = 0.5;
    >> diag(r*ones(N-1,1),-1)
    ans =
             0         0         0         0
        0.5000         0         0         0
             0    0.5000         0         0
             0         0    0.5000         0
    

    *** EDIT ***

    If you want to alter a pre-existing matrix you could just use linear indexing:

    >> DLR = ones(N,N)*7 % start with arbitrary matrix
    DLR =
         7     7     7     7
         7     7     7     7
         7     7     7     7
         7     7     7     7
    >> N = size(DLR,1); % get the row size
    >> DLR(2:N+1:N*(N-1)) = r % linear indexing the lower diagonal
    DLR =
        7.0000    7.0000    7.0000    7.0000
        0.5000    7.0000    7.0000    7.0000
        7.0000    0.5000    7.0000    7.0000
        7.0000    7.0000    0.5000    7.0000
    

    This even works for non-square matrices. E.g.,

    >> X = 8*ones(5,7) % start with arbitrary non-square matrix
    X =
         8     8     8     8     8     8     8
         8     8     8     8     8     8     8
         8     8     8     8     8     8     8
         8     8     8     8     8     8     8
         8     8     8     8     8     8     8
    >> N = size(X,1); % get the row size
    >> X(2:N+1:N*(N-1)) = r % linear indexing the lower diagonal
    X =
        8.0000    8.0000    8.0000    8.0000    8.0000    8.0000    8.0000
        0.5000    8.0000    8.0000    8.0000    8.0000    8.0000    8.0000
        8.0000    0.5000    8.0000    8.0000    8.0000    8.0000    8.0000
        8.0000    8.0000    0.5000    8.0000    8.0000    8.0000    8.0000
        8.0000    8.0000    8.0000    0.5000    8.0000    8.0000    8.0000