Hot answers tagged sparse-arrays
14
Use ArrayRules[]:
m = SparseArray[{2, 2} -> i];
mc = SparseArray[ArrayRules[m] /. i -> -i, Dimensions[m]];
MatrixForm[mc]
$\begin{pmatrix}0&0\\0&-\mathtt{i}\end{pmatrix}$
13
J. M. has shown you a workaround using ArrayRules and as others mentioned, using Conjugate is more prudent. However, to answer your primary question — "Why doesn't ReplaceAll work on SparseArray?", it is because SparseArray is atomic.
In other words, SparseArray objects are "indivisible" and the data contained in them can only be accessed in specific ways ...
13
array0 = {{72, 32, 64}, {18, 8, 16}, {63, 28, 56}};
array1 = SparseArray[Band[{# - 1 + Length@array0[[#]], #}, Automatic, {-1, 1}] ->
array0[[#]] & /@ {1, 2, 3}, {5, 5}];
array1 // MatrixForm
Update: Generalizing for arbitrary matrix input:
rttF = Function[{mat}, With[{dims = Dimensions[mat]},
SparseArray[Band[{# - 1 + Last@dims, #}, ...
12
As Silvia notes in the comments, this behaviour is because of the predictive interface that is new in version 9. Mathematica tries to inspect the contents of the output to determine which contextual menu options to show in the suggestions bar depending on whether it is an array of integers/reals/mixed or if it is square/rectangular, etc. My guess is that ...
10
I found a way to dramatically improve the performance of this algorithm by using the undocumented function SparseArray`KrylovLinearSolve. The key advantage of this function is that it seems to be a near-analog of MATLAB's pcg, and as such accepts as a first argument either:
a square matrix, or a function generating a vector of length equal to the length ...
10
This question came up in Chat the other day. Here is the solution I proposed.
banded[n_Integer?EvenQ] :=
With[
{main = RandomReal[99, n - 1],
side = SparseArray[{}, n - 2, -0.5]},
SparseArray[{i_, i_} :> main[[i]], n - 1] +
Sum[side ~DiagonalMatrix~ i, {i, {-1, 1}}]
]
This uses several tricks and observations. Credit for the first ...
10
I have reported this as a bug. Having said that, here is some more info:
Note that when you use:
am = AdjacencyMatrix@RandomGraph[{25000, 50000}];//N
you do not see the issue. So this is only an integer sparse array issue. What happened until V8 internally is that there is a loop for adding each sparse array as a binary operation. E.g. something like:
...
9
The determinant computation is a matter of memory use in terms of how much we want to store for subdeterminants of a Laplace expansion. Mathematica simply refuses to go that route after 11x11. YOu can do your own as below.
myDet[mat_] /; Length[mat] <= 4 := Det[mat]
myDet[mat_] :=
myDet[mat] =
Sum[mat[[1, j]]*myDet[Drop[mat, {1}, {j}]], {j, ...
8
The message tells you what`s wrong:
SparseArray::dims: The dimensions 11.` in ...are not given as a list of positive machine integers.
You should use something like Round[n+1] as last part.
Your comment
Isn't n +1 an integer though? 4/.2 + 1 = 21?
No. Mathematica makes a distinction between exact Integers and numeric values. In your formula, the ...
8
Given the millions of times that code will be run, for a size range of about 1000, all I could think to speed up @Mr.Wizard 's code is to memoize what stays fixed
i : diags[n_] :=
i = With[{side = SparseArray[{}, n - 2, -0.5]},
Sum[side~DiagonalMatrix~i, {i, {-1, 1}}]];
banded2[n_Integer?EvenQ] :=
With[{main = RandomReal[99, n - 1]},
...
7
Mathematica has, I think, very efficient SparseArray functionality. SarseArrays are supported by a wide variety of functions, e.g LinearSolve, Eigensystem... The SparseArray is stored in CSR (Look for the SparseArray entry). If you are interested here is a description of the internals. For the Import/Export you could either make use of the HarwellBoeing ...
7
In addition to the answers given (ArrayFlatten), there may be cases when the SparseArray-s need to be accumulated one-by-one, and keeping them all in memory at the same time may be too expensive. I've written a generic function to gradually accumulate SparseArray-s. Here is the code:
This is the low-level API for SparseArray construction / deconstruction, ...
7
If you need a batch update, then the answer is in my comment you linked. If you need element-by-element, then there are two cases:
Most of values you update are non-zero (or, generally, not equal to default element). In this case, I believe the answer of @Mr. Wizard is optimal, and you should expect update of a single element to be constant time.
Most ...
7
You can reduce a lot of the computations by exploiting the symmetry in the problem. Observe the following example:
Notice that the 4D matrix is actually a Toeplitz matrix where each element is a 2D matrix, which themselves are Toeplitz matrices. So you really need to only compute the first row in the top line of 2D matrices (here, 9 elements of total 81) ...
6
Since the sum goes over the last index of $e$ and the first index of $A$, it is directly done by using Dot:
dim = 5;
e = Array[\[ScriptE], Table[dim, {dim}]];
a = Array[\[ScriptA], Table[dim, {2}]];
c = e.a;
Here I defined the arrays with the appropriate dimensions but suppressed the output because it's too long for five dimensions.
Another ...
6
This works with matrix of any size (remove Reverse to get it in other direction)
rotate45[m_] :=
SparseArray@
MapIndexed[
Band[{#2[[1]], Length@m + #2[[1]] - 1}, Automatic, {1, -1}] ->
Reverse@# & , m]
MatrixForm[rotate45[{{72, 32, 64}, {18, 8, 16}, {63, 28, 56}}]]
0 0 64 0 0
0 32 0 16 0
72 0 8 0 56
0 18 0 28 ...
6
For any number of dimensions ( two versions):
rot[m_] := Transpose@SparseArray[ Flatten@Map[Band[#] -> Transpose[m][[#[[1]]]] &,
Permutations /@ IntegerPartitions[Length@m + 1, {2}], {2}]]
or (keeping it short)
rot[m_]:= With[{t = Transpose},
t[SparseArray[Band@#-> t[m][[#[[1]]]]&/@ t@{#, ...
6
This is not an answer, but may be it is :) as I do not have time to fully understand the question, just picked up few terms, but just in case, I thought I mention this.
Mathematica 8 already has Krylov method in LinearSolve ! so, if you are just looking to use these methods to solve Ax=b, it is already there.
Here is an example from my code (I used these ...
6
I believe that Part works quite well.
sa = SparseArray[RandomInteger[{1, 10000}, {5000, 2}] -> 1];
new = RandomInteger[{1, 7000}, {5000, 3}];
(sa[[#, #2]] = #3) & @@@ new; // Timing
{0.078, Null}
Notice that this is being done one element at a time with @@@ and it is still very fast.
6
If exporting the SparseArray does not work directly, you could perhaps use
sa=SparseArray[;;;]
sa["NonzeroPositions"]
sa["NonzeroValues"]
and then reconstruct the SparseArray in the other tool. I understand that this is most likely not ideal but it could work. Also, someone else might know better, I am not sure the RSA can deal with rank > 2 matrices.
5
The first Google hit for "compressed sparse column" is this page, which explains that it's also called the Harwell-Boeing format. If this is what you need, this format is supported by Mathematica.
5
Here is a string processing way of extracting the "x-axis" data from the XPM file that you gave. I'll assume that you have already imported the all of the file's records into the string text - e.g. using text = Import[filename,"String"], though I haven't tested this as I actually copied (then pasted into an empty string) the contents of the XPM file quoted ...
5
Sparse multiplication with a circular matrix corresponds to a convolution; on a trivial
example let us compare:
matrix = SparseArray[{Band[{1, 1}] -> 2, Band[{1, 2}] -> 1, Band[{2, 1}] -> 1}, {15, 15}];
vec = SparseArray[5 -> x, 15]; matrix.vec // Normal
(* ==> {0, 0, 0, x, 2 x, x, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)
versus
a = SparseArray[5 ...
5
When you are flattening the expression, you are asking Mathematica to reserve memory for at least
Total@Cases[EqL2, SparseArray[x_, y_, z__] :> Times @@ y]
(*322850400 elements *)
To be more precise, you are only filling
Length@Select[Flatten@Cases[EqL2, s_SparseArray :> ArrayRules@s] /.
Rule ...
5
You might indeed be missing something.
The natural way to create such arrays is with Array (or ParallelArray) and the natural way to create such a lookup table (which is a great idea) is by "memoizing" the functional argument of Array.
Notice that you could change $j$ and $\phi$ so that the indexes $a,b,c,d$ range from $1$ up to some integer; you are ...
4
Flatten[MapIndexed[{Sequence @@ #2, #1} &,
Import["ExampleData/elements.xls"] [[1]], {2}], 1] // TableForm
Requested explanation:
Import["ExampleData/elements.xls"][[1]]
Gets the first sheet in the file
MapIndexed[{Sequence @@ #2, #1} &, ...... , {2}]
Generates tuples of the form {posx, posy, cellValue}
Flatten[........, 1]
...
4
Shorter form of kguler's general function:
f[a_?MatrixQ] := Dimensions[a] /. {y_, x_} :>
SparseArray[Band[{# - 1 + x, #}, Automatic, {-1,1}] -> a[[#]] & ~Array~ y, x + y - {1,1}]
{{72, 32, 64}, {18, 8, 16}, {63, 28, 56}} // f // MatrixForm
J. M.'s code in my own style (just because I feel like it):
Table[#2 ~Diagonal~ k ~Riffle~ 0 ...
2
I have described the details here and here. The second post describes the version number of the sparse array implementation, which is still at version 1. So no big changes since it's introduction and V9.
If you like to read about sparse arrays I can recommend this from Tim Davis.
2
It may not be highly time-efficient (read this) but you can make Part assignments to a SparseArray object just as you would a conventional array, therefore you merely need to replace your ConstantArray with:
SparseArray[{}, {n*n, n*n}]
You can also specify a different background for the array with the third argument:
SparseArray[{}, {n*n, n*n}, 5]
...
1
An old-fashioned I guess rotation of indices.
Turn[m_?MatrixQ] :=
With[{ax = {1, Length[First@m]}},
MapIndexed[Round[Composition[
ScalingTransform[Sqrt[2] {1, 1}, ax],
RotationTransform[Pi/4., ax]]@#2] -> #1 &,
m, {2}]] // Flatten // SparseArray
{{72, 32, 64}, {18, 8, 16}, {63, 28, 56}} // Turn // Normal
(* ...
Only top voted, non community-wiki answers of a minimum length are eligible

