MATLAB: How to create a block diagonal matrix from the slices of a 3D matrix

block matrix from a 3d matrix

I have a large 3D matrix (K) composed of 200 slices , and I want to create a block diagonal matrix from the slices of it without looping. For example
K(:,:,1) =[1 2;3 4]
K(:,:,2) =[5 6;7 8]
K(:,:,3) =[9 10;11 12]
.
.
.
K(:,:,200) =[1 10;13 15]
if we assume the number of slice is 3, the output should be
1 2 0 0 0 0
3 4 0 0 0 0
0 0 5 6 0 0
0 0 7 8 0 0
0 0 0 0 9 10
0 0 0 0 11 12
But how the block diagonal matrix created from all the 200 slices without looping?

Best Answer

k(:,:,1) =[1 2;3 4]
k(:,:,2) =[5 6;7 8]
k(:,:,3) =[9 10;11 12]
q=num2cell(k,[1,2])
blkdiag(q{:})