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

Best way to extend the size and add terms to a SparseArray without expanding

Let's say I have a "small" SparseArray of any size, 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"m any size larger than the previous, 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 by increasing the size and adding new terms?

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.

Another problem is that it doesn't work with further patterns. This fails, because Max[4, i_] doesn't make sense.

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

Furthermore, it all seems too cumbersome, and I'm hoping 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 necessarily) 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.


It seems from the comments that I'm not explaining myself clearly.

SparseArray[SparseArray[{},n],m] with $m>n$ does part of the job, it manipulates a small SparseArray to make it larger, but the issue is how do I add the rules that define some of the new terms in a short robust and idiomatic form?

rhermans
  • 37.4k
  • 4
  • 61
  • 152