Sparse matrix processing: flip sign of top-left entries of the matrix
f[A_?MatrixQ] :=
With[{B = Reverse[Sqrt[A]]},
Reverse[UpperTriangularize[B] - LowerTriangularize[B, -1]]
]
Usage example:
m = 12000;
n = 120000;
A = SparseArray[RandomInteger[{1, m}, {n, 2}] -> RandomReal[{0, 1}, n], {m, m}];
Anew =f[A]; // AbsoluteTiming // First
0.005143
Test:
(A = Partition[Alphabet[][[1 ;; 9]], 3])// MatrixForm
f[A] // MatrixForm
$$\left( \begin{array}{ccc} \text{a} & \text{b} & \text{c} \\ \text{d} & \text{e} & \text{f} \\ \text{g} & \text{h} & \text{i} \\ \end{array} \right)$$
$$\left( \begin{array}{ccc} -\sqrt{\text{a}} & -\sqrt{\text{b}} & \sqrt{\text{c}} \\ -\sqrt{\text{d}} & \sqrt{\text{e}} & \sqrt{\text{f}} \\ \sqrt{\text{g}} & \sqrt{\text{h}} & \sqrt{\text{i}} \\ \end{array} \right)$$
Btw.:
While trying to solve the problem, I found the following solution:
SparseArray[
Replace[ArrayRules[Sqrt[sparseArray]],
x_ /; x[[1, 1]] - x[[1, 2]] > 0 :> x[[1]] -> -x[[2]]
, {1}]
]
Not incredibly fast, but not too slow either.
nn = 4;
sa = SparseArray[Partition[Symbol /@ CharacterRange["a", "z"][[;; nn^2]], nn]];
TeXForm @ MatrixForm @ sa
$\left( \begin{array}{cccc} a & b & c & d \\ e & f & g & h \\ i & j & k & l \\ m & n & o & p \\ \end{array} \right)$
mask = HankelMatrix @@ ({MapAt[-# &, -#, {-1}], #} & @ ConstantArray[1, nn])
TeXForm @ MatrixForm @ mask
$\left( \begin{array}{cccc} -1 & -1 & -1 & 1 \\ -1 & -1 & 1 & 1 \\ -1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 \\ \end{array} \right)$
sa2 = mask Sqrt[sa]
SparseArray[<16>,{4,4}]
TeXForm @ MatrixForm @ sa2
$\left( \begin{array}{cccc} -\sqrt{a} & -\sqrt{b} & -\sqrt{c} & \sqrt{d} \\ -\sqrt{e} & -\sqrt{f} & \sqrt{g} & \sqrt{h} \\ -\sqrt{i} & \sqrt{j} & \sqrt{k} & \sqrt{l} \\ \sqrt{m} & \sqrt{n} & \sqrt{o} & \sqrt{p} \\ \end{array} \right)$
Alternatively, you can use a combination of MapIndexed
and MapAt
:
sa3 = MapIndexed[MapAt[-# &, #, {;; nn - #2[[1]]}] &, Sqrt[sa]];
TeXForm @ MatrixForm @ sa3
$\left( \begin{array}{cccc} -\sqrt{a} & -\sqrt{b} & -\sqrt{c} & \sqrt{d} \\ -\sqrt{e} & -\sqrt{f} & \sqrt{g} & \sqrt{h} \\ -\sqrt{i} & \sqrt{j} & \sqrt{k} & \sqrt{l} \\ \sqrt{m} & \sqrt{n} & \sqrt{o} & \sqrt{p} \\ \end{array} \right)$