matlab 在FOR循环中构建对角线

dgiusagp  于 2022-11-15  发布在  Matlab
关注(0)|答案(3)|浏览(210)

尝试以对角线方式附加到for循环中的矩阵:

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

显然,这是行不通的,因为我正在重写该值。我想构建一个由R1值组成的矩阵,如下所示

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

我可以使用其他技术来实现最终目标,只是好奇它是否可以在for循环中完成

2hh7jdfx

2hh7jdfx1#

只要我们在循环和增长矩阵,这个怎么样?

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
vnjpjtjt

vnjpjtjt2#

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

这应该行得通。

pod7payv

pod7payv3#

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

正如您所说的,for循环不是实现这一点的最佳方式,但确实可以做到。

相关问题