Using ReplaceAll on SparseArray

I'm using SparseArray in a notebook in which I am doing complex conjugation manually, i.e. writing $\sqrt{-1}$ as i and applying /.{i->-i} to perform complex conjugation.

I noticed that ReplaceAll or /. doesn't seem to work on SparseArrays, e.g.

m = SparseArray[{2, 2} -> i];
m /. {i -> -i}


just returns m. Any clues on how to get around this quickly?

-
is it necessary to do this without converting to a normal array? – acl Oct 28 '12 at 13:33
Hm yes I could convert it to normal, perform conjugation, and convert back to sparse. Would be nice if this can be done on the sparse array though. – matimo2 Oct 28 '12 at 13:35
You can't use I (and then Conjugate[])? – J. M. Oct 28 '12 at 13:37
If You are working with own "i" why don't You write own conjugate[] function? You can pack there sparse array conversion and use Your transformation rule. – mmal Oct 28 '12 at 13:37
@mmal yes that's what I've been doing. I just thought this adds computational steps that might be avoided if /. can be used in a straight-forward manner on sparse arrays. – matimo2 Oct 28 '12 at 13:38

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 (e.g., using undocumented arguments to SparseArray) and not by manipulating its FullForm. You can verify that it is indeed atomic, whereas a regular matrix is not:

AtomQ@m
(* True *)

AtomQ@Normal@m
(* False *)


A similar situation arises with Graph objects, which are also atomic. For instance, the following will not work:

Graph[{1 -> 2, 2 -> 3, 2 -> 4}] /. DirectedEdge -> UndirectedEdge


even though // FullForm will show the presence of DirectedEdge in the structure. Hence it is important for you to know which objects are atomic before you try (unsuccessfully) to use replacement rules on them.

To the best of my knowledge, the list of atomic objects (not including undocumented ones) are those with the following heads:

{Symbol, String, Integer, Real, Rational, Complex, SparseArray, BooleanFunction, Graph}

-
Thanks, that's very useful to know. – matimo2 Oct 28 '12 at 14:24
m = SparseArray[{2, 2} -> i];
mc = SparseArray[ArrayRules[m] /. i -> -i, Dimensions[m]];
MatrixForm[mc]


$\begin{pmatrix}0&0\\0&-\mathtt{i}\end{pmatrix}$

-