MATLAB: How to create a block diagonal sparse matrix from a paged array in an efficient way

blockdiagonalMATLABpagedsparse

How can I create a block diagonal sparse matrix from a paged array in an efficient way? The original array is a 3-dimensional array in which the third dimension ranges through the pages and each page contains a block of the block diagonal matrix.

Best Answer

You can create such a matrix using the "repmat", "reshape" and "transpose" operations, by means of the following code:
 
% Sample paged matrix
m=3;n=2;p=4;
A = rand(m,n,p);
% The following create the indices via repmat, reshape and transpose operations
I2 = repmat((1:m)',1,n);
I3 = repmat(I2,1,1,p);
If = repmat((0:m:(p-1)*m),m*n,1); I = I3 + reshape(If,m,n,p);
J2 = repmat((1:n),m,1);
J3 = repmat(J2,1,1,p);
Jf = repmat((0:n:(p-1)*n)',1,m*n)'; J = J3 + reshape(Jf,m,n,p);
%Create the sparse matrix
S = sparse(I(:),J(:),A(:))
If you are using MATLAB R2016b or a more recent release, this code can be simplified by means of implicit expansion
 
m=3;n=2;p=4;
A = rand(m,n,p);
I = repmat((1:m)', 1, n) + permute(m*(0:p-1), [3 1 2]);
J = repmat(1:n, m, 1) + permute(n*(0:p-1), [3 1 2]);
S = sparse(I(:), J(:), A(:))