Extended block diagonal matrix in Matlab

后端 未结 2 787
无人共我
无人共我 2021-01-06 04:47

I know that to generate a block-diagonal matrix in Matlab the command blkdiag generates such a matrix:

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 05:32

    This could be one approach based on kron, tril & triu -

    %// Take all A1, A2, A3, etc in a cell array for easy access and same for B
    A = {A1,A2,A3,A4}
    B = {B1,B2,B3}
    
    %// Setup output array with the A blocks at main diagonal
    out = blkdiag(A{:})
    
    %// logical array with 1s at places where kth diagonal elements are to be put
    idx = kron(triu(true(numel(A)),k) & tril(true(numel(A)),k),ones(size(A{1})))>0
    
    %// Put kth diagonal blocks using the logical mask
    out(idx) = [B{1:numel(A)-k}]
    

    Sample run with k = 1 for 2 x 2 sizes matrices -

    >> A{:}
    ans =
        0.3467    0.7966
        0.6228    0.7459
    ans =
        0.1255    0.0252
        0.8224    0.4144
    ans =
        0.7314    0.3673
        0.7814    0.7449
    ans =
        0.8923    0.1296
        0.2426    0.2251
    >> B{:}
    ans =
        0.3500    0.9275
        0.2871    0.0513
    ans =
        0.5927    0.8384
        0.1629    0.1676
    ans =
        0.5022    0.3554
        0.9993    0.0471
    >> out
    out =
        0.3467    0.7966    0.3500    0.9275         0         0         0         0
        0.6228    0.7459    0.2871    0.0513         0         0         0         0
             0         0    0.1255    0.0252    0.5927    0.8384         0         0
             0         0    0.8224    0.4144    0.1629    0.1676         0         0
             0         0         0         0    0.7314    0.3673    0.5022    0.3554
             0         0         0         0    0.7814    0.7449    0.9993    0.0471
             0         0         0         0         0         0    0.8923    0.1296
             0         0         0         0         0         0    0.2426    0.2251
    

提交回复
热议问题