MATLAB: How to create the upper diagonal block matrix in a specific form.

block matrixlinear algebramatricetriangular matrix

c = input('c ');
g = input('g ');
syms Lambda_n
M = cell(c+1,1);
a_t = min([1:c+1;repmat(c-g+1,1,c+1)]);
for i = 1:c+1
v = zeros(1,c+2-i, 'sym');
v(1)= Lambda_n*i;
MCell = repmat({diag(v)}, 1, a_t(i));
M{i} = blkdiag(MCell{:});
end
B=blkdiag(M{:});
'c' will determine the size of blocks which I already explained to you that they will be in decreasing order. 'g' is basically used in a_t = ,min{j,c-g}. Here a_t determines how many time a block should be repeated. So upto c-g the order of block upper diagonal matrix will be (i+1,i) and from c-g+1 upto c+1 it will be (c-g+1,c-g+1).
This is for the main diagonal block matrix which is shown in the picture. Similarly I want to create the upper diagonal as shown by the red line in the picture. I have tried to creat it using kron function but it was just not what i wanted. Kindly help me with this.

Best Answer

Here is the code that will generate blocks like [O A O;O O A] given the values of c and g.
clear,clc
c = 3;
g = 1;
syms Lambda_n
%replacement for the loop:
A=Lambda_n;
A(c+1,c)=0;
put_A_here=logical([zeros(c-1,1) eye(c-1)]);
big=repmat(sym(0),size(put_A_here).*size(A));
big=insert_matrix(big,A,put_A_here);
function out=insert_matrix(big,small,L)
out=big;
A=reshape(1:numel(small),size(small));
B=repmat({zeros(size(A))},size(L));
B(L)={A};
B=cell2mat(B);
B=B(:);
out(B~=0)=small(B(B~=0));
end