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$

4 Answers 4

2
$\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$
1
$\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$
1
$\begingroup$
list = {{1 + x^3, Tan[y]}, {y^3, 0}};

Using ReplaceAt (new in 13.1)

p = Position[list, Except[0], {2}, Heads -> False]

{{1, 1}, {1, 2}, {2, 1}}

ReplaceAt[list, a_ :> a + O, p]

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

$\endgroup$
1
$\begingroup$

Using SubsetMap:

A = {{1 + x^3, Tan[y]}, {y^3, 0}};
pos = Position[A, Except[0], {2}, Heads -> False]

SubsetMap[# + O &, A, pos]

{{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 and acknowledge you have read our privacy policy.

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