3
$\begingroup$

I discovered a difference between version 12.0 and version 14.0 in how they handle SparseArray within the Table function.

For example:

SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> z}];
Normal /@ Table[%, {z, 0, 1}]

I got

{{{1, 0, 0}, {0, 2, 0}, {0, 0, 3}}, {{1, 0, 1}, {0, 2, 0}, {0, 0, 3}}}

in version 12.0, and

{{{1, 0, z}, {0, 2, 0}, {0, 0, 3}}, {{1, 0, z}, {0, 2, 0}, {0, 0, 3}}}

in version 14.0. This results in much of the code written for version 12.0 being incompatible with version 14.0. I want to maintain the previous format, namely using SparseArray within the Table function, and I hope it runs in version 14.0. What should I do?

$\endgroup$
1

1 Answer 1

2
$\begingroup$

What about this?

array[z_] := 
 SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> z}]
Normal /@ Table[array[z], {z, 0, 1}]

(*{{{1,0,0},{0,2,0},{0,0,3}},{{1,0,1},{0,2,0},{0,0,3}}}*)

Or you can change the position of Normal.

SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> z}];
Table[Normal@%, {z, 0, 1}]

(*{{{1,0,0},{0,2,0},{0,0,3}},{{1,0,1},{0,2,0},{0,0,3}}}*)

You can also consider the following code.

s = SparseArray[{{1, 1} -> 1, {1, 3} -> z, {2, 1} -> 5, {2, 2} -> 
    2, {3, 3} -> 3}]; Table[
 SparseArray[ArrayRules[s] /. z -> i], {i, 0, 1}];
Normal /@ %
$\endgroup$
6
  • $\begingroup$ Thank you very much for your reply. While the Normal function can temporarily resolve this error, it also leads to increased memory consumption. $\endgroup$ Commented Jul 29, 2024 at 16:45
  • $\begingroup$ @sidy What does you mean? If you want to get two SparseArray, you can use my first method, or just generate SparseArray in Table. $\endgroup$ Commented Jul 29, 2024 at 16:52
  • $\begingroup$ Oh yes, I see what you mean.You are right. $\endgroup$ Commented Jul 29, 2024 at 17:01
  • 2
    $\begingroup$ It's not a bug. Please see the 7th bullet point in Incompatible Changes: The internal structure of SparseArray has been changed. It is now treated as a raw object for purposes of pattern matching. $\endgroup$ Commented Jul 29, 2024 at 18:25
  • $\begingroup$ @Domen You are right. But is this structure really good? Number 1/2 is an atom, but expression 1/a is not. Meanwhile, List is never an atom. So why should a SparseArray(especially one with variables) be a raw object? $\endgroup$ Commented Jul 30, 2024 at 1:16

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.