Skip to main content
4 of 7
added 261 characters in body
rhermans
  • 37.4k
  • 4
  • 61
  • 152

Best way to extend the size of a SparseArray

Let's say I have a "small" SparseArray, in the example $2\times2$

MatrixForm[
    m2 = SparseArray[{{i_,i_}->1,{1,2}->a},2]
]

enter image description here

I want to expand it to a "Large", for example, $4\times4$ SparseArray without rewriting it.

let's say

m4test = SparseArray[{{i_,i_}->1,{1,2}->a, {3,4}->b },4]

enter image description here

How do I efficiently (not expanding and contracting) do I transform m2 into m4?

Due diligence

I didn't find a similar question on the site, and ChatGPT doesn't seem to understand how to program for general cases.

I have tried this,

extendSparseArray[sa_, rules_] := SparseArray[
    Join[rules, ArrayRules[sa]]
    , Max[Join[Dimensions[sa],Flatten@rules[[All,1]] ] ]
]

MatrixForm[
    extendSparseArray[m2, {{3,4}->b}]
]

enter image description here

Which does part of the job. Notice it conserves the default value, because

ArrayRules[SparseArray[{{i_,i_}->1}, 4, x]]
(* {{1, 1} -> 1, {2, 2} -> 1, {3, 3} -> 1, {4, 4} -> 1, {_, _} -> x} *)

which includes the rule {_, _} -> x. Unfortunately, it misses the other general rule {i_,i_}->1. Furthermore, it all seems too cumbersome, and I'm hopping I'm missing something more fundamental.

Perhaps it's not reasonable to expect to recover the pattern rule, in that case at least the default value (in this case zero, but not necesarily) should be conserved.

What are simple and idiomatic ways to achieve this and which one performs the best?

The examples are meant to be minimal to facilitate the discussion, I will use this with larger and more complex SparseArray expressions.

rhermans
  • 37.4k
  • 4
  • 61
  • 152