Search code examples
matlabdiagonal

Build Diagonal in for loop


Trying to append to a matrix in a for loop diagonally:

for ii=1:10
     R1 = [1,2;3,4]; Matrix is always 2x2 but different values each iteration 
     cov = blkdiag(R1);
end

Obviously this won't work since I am rewriting over the value. I want to build a matrix that consists of R1 values such as this

[ R1,0,0,0...,
   0,R1,0,0...]

I can accomplish the end goal employing other techniques just curious if it can be done in the for loop


Solution

  • R1 = [1,2;3,4];                              %// initial R1 matrix
    CurrentOut = R1;                             %// initialise output
    for ii = 1:10
        R1 = [1,2;3,4];                          %// placeholder for function that generates R1
        [A,B] = size(CurrentOut);                %// get current size
        tmpout(A+2,B+2)=0;                       %// extend current size
        tmpout(1:A,1:B) = CurrentOut;            %// copy current matrix
        tmpout(A+1:end,B+1:end) = R1;            %// add additional element
        CurrentOut=tmpout;                       %// update original
    end
    

    as you said, a for loop is not the best way of doing this, but it can indeed be done.