James Nugent
James Nugent

Reputation: 3

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

Upvotes: 0

Views: 154

Answers (3)

陈俊仕
陈俊仕

Reputation: 1

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

This should work.

Upvotes: 0

Adriaan
Adriaan

Reputation: 18174

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.

Upvotes: -1

beaker
beaker

Reputation: 16791

As long as we're looping and growing matrices, how about this?

for ii = 1:10
   R1 = [1 2; 3 4];   %// placeholder for function that generates R1
                      %// move this line and next before loop if R1 is static
   [m,n] = size(R1);
   cov(end+1:end+m,end+1:end+n) = R1;
end

Upvotes: 2

Related Questions