1
$\begingroup$

I would like to add a certain placeholder O to any nonzero element of a matrix. The matrix has elements which are not number but complicated symbolic expressions. Take for example:

A = {{1 + x^3, Tan[y]}, {y^3, 0}};

Following the solution outlined here, I tried

B = A /. {x_ /; x != 0 :> x + O} // MatrixForm

But this evidently replaces adds O to any number within the matrix:

{{1 + O + x^(3 + O), Tan[y]}, {y^(3 + O), 0}}

How could that be modified to make it work in that case as well? The output I am after is:

{{1 + x^3 +O, Tan[y]+O}, {y^3+O, 0}}

$\endgroup$
1
$\begingroup$

The output I am after is: {{1 + x^3 +O, Tan[y]+O}, {y^3+O, 0}}

One way might be

ClearAll[x,O];
A = {{1 + x^3, Tan[y]}, {y^3, 0}}
newA = Map[If[# =!= 0, # + O, #] &, A, {2}]

Mathematica graphics

$\endgroup$
0
$\begingroup$

Using an undocumented way of constructing SparseArrays:

A = {{1 + x^3, Tan[y]}, {y^3, 0}};
AO = Normal@With[{a = SparseArray[A]},
   SparseArray @@ {Automatic, Dimensions[a], a["Background"], {1, {
       a["RowPointers"],
       a["ColumnIndices"]
       },
      a["NonzeroValues"] + O}}
   ]

{{1 + O + x^3, O + Tan[y]}, {O + y^3, 0}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.