# Tag Info

11

Pattern sparse arrays are used, for example, in NDSolve to specify the structure of a Jacobian. This can save significant time while integrating a differential equation. In other words pattern sparse arrays are useful if one knows something about the structure of a sparse array but not (yet) about the values. There are some examples in the FEM Programming ...

5

Using the following to sim data of the actual size in your example: length = RandomInteger[{1500, 2000}, 30000]; value = Table[RandomReal[{}, length[[i]]], {i, 30000}]; start = RandomInteger[{1, 118000}, 30000]; This takes a few seconds on a friggin' loungebook so I'd venture under a second on real hardware: totLen = 120000; accum = ConstantArray[0., ...

1

If all you need is the sum at the end, why construct the matrix at all? result = ConstantArray[0, 20]; Do[ result[[start[[i]] - 1 + Range[Length@value[[i]]]]] += value[[i]], {i, 4}]; result For such a sparse operation such a loop might just be the most efficient thing you can do. Edit, a more mathematia-esque approach: Fold[#1 + ...

3

To generate an array of rules without using Table (cf. your comment under yohbs' answer), and to use it to construct a sparse array (see the updates for Method 2): (* Method 1 *) positions = Transpose[{ Join @@ MapThread[ConstantArray, {Range@4, length}], Join @@ MapThread[Range[#1, #1 + #2 - 1] &, {start, length}]}] rules = ...

2

First of all, as a thumb rule - if you're using loops in Mathematica, you're probably not doing it right. See here and here for more details. Second, the whole point of a sparse array is that you don't need to allocate all the memory for all the entries in advance, like you do with the command sparseA = ConstantArray[...]. Here's how it should be done: ...

1

Your sample spdat generated from random numbers is of course likely to be just an example for this question, but nonetheless in the interest of thoroughness I would like to point that in the literal case you cannot be sure to recover your spdat from spmat, because your spdat may contain duplicate directives, only one of which is retained when you generate ...

4

Using Export directly "just works": In[23]:= mat = SparseArray[DiagonalMatrix[2^Range[0, 10]]]; In[24]:= file = Export[CreateTemporary[], mat, "Package"]; In[25]:= FilePrint[file] During evaluation of In[25]:= (* Created with the Wolfram Language : www.wolfram.com *) SparseArray[Automatic, {11, 11}, 0, {1, {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, {{1}, ...

2

Here are two different ways of getting spdat from spmat: Join[#[[1]], {#[[2]]}] & /@ (ArrayRules[spmat]) or (this is chuy's suggestion) MapThread[Append, {#["NonzeroPositions"], #["NonzeroValues"]}] &@spmat

Top 50 recent answers are included