MATLAB: How to copy a sub-matrix/vector along diagonal of a larger matrix with varying number of sub-matrices

blkdiagmatrix

I want to create a matrix below where I copy A = [1 2 3] allow the diagonal of a matrix.
[ 1 2 3 0 0 0 0 0 0 0 0 0
0 0 1 2 3 0 0 0 0 0 0
0 0 0 0 0 0 1 2 3 0 0 0
0 0 0 0 0 0 0 0 0 1 2 3]
I know I can use blkdiag(A ,A, A, A) which will do the job however the number of parameters vary in my code. Sometimes, there may be five A vectors or 20 A vectors that I need to create such a matrix. Let's say this is a variable that the user inputs
How can I do this efficiently in code?

Best Answer

You can use comma-separated list expansion to do this automagically:
n = 20;
A = [1 2 3];
Ac = repmat({A},n,1);
blkdiag(Ac{:})