Hot answers tagged

10

The following code defines AndRuleDelayed to take a number of patterns followed by a (single) replacement and build a rule. The rule matches if and only if all patterns match, and the replacement can involve variables from any of the patterns. If the same variable name appears in two patterns, the combined pattern will only match if all occurrences of that ...


6

Or you can use Map A = {{a, b, c, d, e}, {f, g, h, j}}; A /. (# -> 0 & /@ {a, b, c}) Update: or to have fun. Fold[#1 /. #2 -> 0 &, A, {a, b, c}]


6

In terms of generating the replacement rule efficiently, you can do the following: A = {{a, b, c, d, e}, {f, g, h, j}}; A /. Thread[{a, b, c} -> 0] (*{{0, 0, 0, d, e}, {f, g, h, j}}*)


4

You can achieve either result depending on the order of evaluation. As Marius pointed out, once a rule out of a set of rules has been applied to a specific part of an expression, no further rules will be applied to that expression. Notice the difference between applying both rules at the same time, and applying them one after the other: (* At the same time,...


3

As a general case where you want to replace all the arguments, (b'[x y/z] + z b''[x y/z]) /. Derivative[n_][b_][x_] :> Derivative[n][b][z] z b''(z)+b'(z) No matter what was your previous argument, it will be replaced by z.


3

I would argue that the most idiomatic solution is A /. a | b | c -> 0


3

Since space is implicit Times similar methods to Convert head Times to List can be applied: Block[{Times = List}, ToExpression @ "{1 2 3 4 5 6 7 8}"] // First {1, 2, 3, 4, 5, 6, 7, 8} Though in this case a much shorter method works too: ToHeldExpression[expression] ~Level~ {3} {1, 2, 3, 4, 5, 6, 7, 8}


2

As pointed out by Leonid Shifrin in comments, the behaviour you observe is not specific to associations, but is true of any function with the attribute HoldAll (or HoldAllComplete, or the relevant HoldFirst or HoldRest). As an example I use Hold. The simple rule {a_, b_}:>a+b does not force evaluation. To force it, you can use With in the right-hand ...


1

May be, like this: A = {H2*H3*Ax[x, y, z], H1*H3*Ay[x, y, z], H1*H2*Az[x, y, z]}; Then expr = 1/(H1*H2*H3)*Inactive[Div][A, {x, y, z}] (* Inactive[Div][{H2 H3 Ax[x, y, z], H1 H3 Ay[x, y, z], H1 H2 Az[x, y, z]}, {x, y, z}]/(H1 H2 H3) *) And you may substitute: expr1=expr /. Thread[{H1, H2, H3} -> {1, 1, 1}] (* Inactive[Div][{Ax[x, y, ...


1

You can change the substitution rule a little bit to avoid the power. (1 + (a (α + β))/(b^2 + c^2) + ((α + β)^2 a^2)/(b^2 + c^2)) /. a -> d (b^2 + c^2) 1 + d (α + β) + (b^2 + c^2) d^2 (α + β)^2


1

b'[xy/z] + z b''[xy/z] /. {xy/z -> z} gives me an output of b'[z]+z b''[z] Is that what you meant?


1

Activate@Replace[Inactive[f][3],3->1, Infinity] 1 or Replace[Hold@f[3], 3 -> 1, Infinity] // ReleaseHold 1



Only top voted, non community-wiki answers of a minimum length are eligible