# Partitioning a sparse matrix into sparse sub-matrices

Given a normal matrix, for example

m = Array[a,{4,4}]


which has dimensions {4,4}, I can partition it by using:

m2 = Partition[m,{2,2}],


which has dimensions {2,2,2,2}.

Now, if m is a sparse array, for example:

m = SparseArray[Table[{i,i}->i,{i,1,4}],{4,4}]


I would like to be able to partition it in a similar manner but with the result being a sparse matrix. The command Partition always yields a dense matrix. Of course, I could do something like:

SparseArray[ArrayRules[Partition[m,{2,2}]]]


but it would be inefficient since it creates a dense matrix inbetween.

• I'm not sure how to accomplish what you want, but I thought I'd add that for your example m you can do m=SparseArray[{i_,i_}:>i,{4,4}] – evanb Nov 15 '17 at 21:46
• Why not use SparseArray@(Partition[m, {2, 2}]) ? – José Antonio Díaz Navas Nov 15 '17 at 22:01
• @jose Because SparseArray@Partition[m,{2,2}] would first apply Partition[#,{2,2}]& to the sparse array, converting it to a dense array, and then reconvert it into another sparse array. – Javier Garcia Nov 15 '17 at 22:21

new = ArrayReshape[m, {2,2,2,2}];
new //OutputForm
new //MatrixForm //TeXForm


SparseArray[<4>, {2, 2, 2, 2}]

$\left( \begin{array}{cc} \left( \begin{array}{cc} 1 & 0 \\ 0 & 0 \\ \end{array} \right) & \left( \begin{array}{cc} 0 & 2 \\ 0 & 0 \\ \end{array} \right) \\ \left( \begin{array}{cc} 0 & 0 \\ 3 & 0 \\ \end{array} \right) & \left( \begin{array}{cc} 0 & 0 \\ 0 & 4 \\ \end{array} \right) \\ \end{array} \right)$

Note that ArrayReshape and Partition yield different results:

Normal @ ArrayReshape[m, {2,2,2,2}] == Partition[m, {2,2}]


False

If you want to have ArrayReshape return the same matrix as Partition, then you need to post-process with Transpose:

Equal[
Normal @ Transpose[ArrayReshape[m, {2,2,2,2}], {1,3,2,4}],
Partition[m,{2,2}]
]


True