MATLAB: Concatenate x amount of matrices

arrayMATLABmatrices

I have a FEM problem that i want to solve with a matlab script so that it can be used for future questions. I´m trying to concatenate x number of known 4×4 matrices diagonaly to form a large 2(x+1),2(x+1) matrix. Examples would be one 4×4 matrice into a 4×4 matrice or three 4×4 matrice into a 8×8 matrix. in the end i want it to look like this but on a bigger scale:
A=[k1 -k1;-k1 k1], B=[k2,-k2; -k2 k2] => C=[k1 -k1 0 ; 0 -k1 + k2 k2; 0 -k2 k2]
I have tried to solve this with this code:
K = sym(zeros( 2*(x+1) , 2*(x+1) ) );
for k = 1:x
K(k:2*((k+1)),k:(2*(k+1))) = K( k:(2*(k+1)) , k:(2*(k+1)) )+C{x};
end
This is part of a script there the user defines the amount of matrices. I made similar loop so i belive its the indexing within the loop that is the problem but dont know how to solve it. Is it possible to solve this problem simply within this loop?
Thanks in advance

Best Answer

x=length(C);
K=zeros(2*(x+1));
for i=1:x
K=K+blkdiag(repmat(zeros(2),i-1,i-1),C{i},repmat(zeros(2),x-i,x-i));
end