Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sparse block diagonal matrix in Matlab

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?

like image 886
littleO Avatar asked Oct 19 '22 05:10

littleO


1 Answers

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
like image 166
Luis Mendo Avatar answered Oct 27 '22 08:10

Luis Mendo