4
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ 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}] $\endgroup$
    – evanb
    Nov 15, 2017 at 21:46
  • $\begingroup$ Why not use SparseArray@(Partition[m, {2, 2}]) ? $\endgroup$ Nov 15, 2017 at 22:01
  • $\begingroup$ @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. $\endgroup$ Nov 15, 2017 at 22:21

1 Answer 1

6
$\begingroup$

Use ArrayReshape:

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)$

Addendum

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.