MATLAB: Create block diagonal matrix by slicing blocks from non-square matrix

blkdiagMATLABreshape matrix

I have a large 3nx3 matrix comprised of 'n' 3×3 matrices stacked one after the other like:
A=[A1;A2;…An] (A1, a2, … An are 3×3 matrices and n is of the order of 5000)
I am trying to reshape this matrix into a block diagonal matrix B that is of size 3nx3n in preparation for solving a system of linear equations. I know how to do this for a small number of matrices by manually providing the matrices as input to the blkdiag() function. However, this strategy is not viable for a large n. I need some input on the following aspects:
  1. I believe I can utilize loops to obtain the necessary result. Is there a different/more optimized way of going about creating the large block matrix while avoiding loops as much as possible?
  2. Can I create a list of matrices that can be input to blkdiag()? I tried using cell arrays to store the individual matrices but this does not work.
  3. Is the above strategy to solve the system flawed? Can you suggest a simpler/better way?
Thank you all in advance, Saradhi

Best Answer

a=magic(3);
n=4;
A=repmat(a,n,1);
B=mat2cell(A,3*ones(1,n),3);
C=blkdiag(B{:})