MATLAB: Cell and Mat problem

cell matrixmatrixstore

A=[1 2;5 2]
B=[2 1;4 5]
I want this as
Ans:
C=[1 2 0 0
5 2 0 0
0 0 2 1
0 0 4 5]
Actualy I want to store matrixes in a single matrix (as given in Ans) because my prog generate 10 matrix.

Best Answer

You can use blkdiag:
>> A = [1,2;5,2];
>> B = [2,1;4,5];
>> blkdiag(A,B)
ans =
1 2 0 0
5 2 0 0
0 0 2 1
0 0 4 5
If you are generating those matrices in a loop, then you can simply put them into a cell array first:
>> N = 5;
>> C = cell(1,N);
>> for k = 1:N; C{k} = randi(9,2); end % <- your loop
>> blkdiag(C{:})
ans =
1 2 0 0 0 0 0 0 0 0
3 2 0 0 0 0 0 0 0 0
0 0 3 1 0 0 0 0 0 0
0 0 4 9 0 0 0 0 0 0
0 0 0 0 9 5 0 0 0 0
0 0 0 0 5 4 0 0 0 0
0 0 0 0 0 0 9 2 0 0
0 0 0 0 0 0 4 8 0 0
0 0 0 0 0 0 0 0 4 4
0 0 0 0 0 0 0 0 3 1