Suppose B is a cell array of sparse matrices in Matlab, and I want to form a sparse block diagonal matrix M whose diagonal blocks are the matrices stored in B. What's the easiest / most efficient way to do that?
Use blkdiag
on a comma-separated list generated from the cell array:
result = blkdiag(B{:});
For example, with
B = {sparse([1 0 0; 2 2 0; 3 3 3]), 4*speye(2)};
this produces
>> result
result =
(1,1) 1
(2,1) 2
(3,1) 3
(2,2) 2
(3,2) 3
(3,3) 3
(4,4) 4
(5,5) 4
>> full(result)
ans =
1 0 0 0 0
2 2 0 0 0
3 3 3 0 0
0 0 0 4 0
0 0 0 0 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With