Questions about Mathematica's rule-based replacement functionality, including functions such as Rule (->), Replace, ReplaceAll (/.) and ReplaceRepeated (//.).

learn more… | top users | synonyms (4)

47
votes
3answers
1k views

Replace inside Held expression

I wish to make functional replacement inside Held expression like this: ...
30
votes
2answers
1k views

Best practice of passing a large number of parameters to functions

I have a number of functions that all take a large number of parameters. I am wondering what is the best practice of passing these parameters to those functions. I could, of course, simply specify ...
26
votes
1answer
937 views

replacement rules from a pattern and a matching expression

(This seems to be a very basic necessity in a language having pattern-matching capabilities such as Mathematica, yet I struggled for many hours to find a common solution to this problem.) Suppose ...
25
votes
3answers
2k views

Extracting values from nested rules in JSON data

I have been using Mathematica to analyse some data from the StackExchange API. It is conveniently available in JSON form, which Mathematica interprets as replacement rules. However, some of the rules ...
20
votes
2answers
1k views

Mathematica for Computer Scientists

Background I've coded in C/Scheme for 10 years. I have a BS CS. I've recently become very interested in pattern-matching (lisp's match macro), and term rewriting systems, which brought me to ...
18
votes
3answers
1k views

Using results of Reduce

Suppose I have function f: f[x_, y_] := 50000 + x 30000 + y 35000; Now I want to find the x and y when f[]<=200000. I use Reduce: ...
18
votes
3answers
324 views

Options which require RuleDelayed

For some functions in Mathematica it is important to use RuleDelayed. One prominent example is the EvaluationMonitor for ...
16
votes
1answer
308 views

Why is ReplaceAll behaving like this?

I'm learning to use the ReplaceAll function and I found the behavior of which is quite confusing. For Sqrt[f[x, y]] /. f[___] -> u Mathematica returns ...
15
votes
6answers
4k views

Replacing composite variables by a single variable

To replace a single variable by another variable, one can simply use the the replace all (/.) operator (e.g., ...
15
votes
2answers
247 views

Why Infinity /. _?(# < 6 &) -> 0 replaces Infinity with ComplexInfinity?

Suppose I define a matrix: mat = { {Infinity, 4, 9}, {6, Infinity, 10}, {8, 9, Infinity} }; Now I want to replace all values smaller than ...
14
votes
4answers
1k views

How to change element color in Periodic Table?

The command ColorData["Atoms", "Panel"] generates a periodic table. As I don't want to reinvent the wheel, I asked myself how to change the color of each cell ...
13
votes
4answers
328 views

Replacing parts of a held expression with held parts of another expression

I'm applying the Trott-Strzebonski technique in order to replace inside a held expression. ...
13
votes
1answer
591 views

rule-based implementation of an algorithm

When I first started learning about rule-based programming with Mathematica, I tried to translate this algorithm for computing the convex hull of a set of 2-D points in $O(n \log(n))$ time, to use ...
13
votes
1answer
454 views

Transform an expression into a graph that can be plotted with TreeGraph (not TreeForm)

I would like to plot an expression (like TreeForm does), but using the new TreeGraph functionality. ...
13
votes
1answer
336 views

Is everything in Mathematica ultimately stored as a rule?

My current understanding about Mathematica is that everything, at the lowest level, ends up as replacement rules. First question: is this true? Second question: does Mathematica "gloss over" these ...
12
votes
7answers
992 views

How to assign a list of numbers into letter grades

Here is my list: ...
12
votes
7answers
4k views

How do I replace a variable in a polynomial?

How do I substitue z^2->x in the following polynomial z^4+z^2+4? z^4+z^2+4 /. z^2->x ...
12
votes
4answers
357 views

How to replace every possible $A+B$ and $AB$ in expansion of $(A+B)^{10}-A^{10}-B^{10}$ with $x$ and $y$, respectively?

I would like to replace every possible $A+B$ and $AB$ in expansion of $(A+B)^{10}-A^{10}-B^{10}$ with $x$ and $y$, respectively. How to do it with the simplest code in Mathematica? For example, ...
12
votes
3answers
310 views

Equivalent of ReplaceAll for Associations?

Is there a nice (built-in) way to apply Replace-style rules to key-value pairs in an association? Something like ...
12
votes
4answers
413 views

“Strange” behavior of Rule

According to the Help lhs->rhs evaluates rhs immediately. How to understand the output of the following code? ClearAll@x; {1, 3.5} /. x_?IntegerQ -> {x} ...
12
votes
2answers
265 views

ReplaceRepeated seemingly omits some rules

Is there a simple way in Mathematica to prevent rule reordering? Let me give an example: ...
12
votes
1answer
295 views

StringReplace, ReplaceAll and Rule interact in a bizarre way

I have the following pair of things: ClearAll[foo, labeledFoo]; labeledFoo = {"FooBarBazQuux", foo}; This works like you'd expect: ...
11
votes
3answers
429 views

Replace operators

/. can be used to replace variables but how can one replace operators. For example in a * b, ...
11
votes
6answers
397 views

For a given expression: if it appears, remove it, but if it is absent, add it

While reformatting Szabolcs's code from (42660) I noticed this interesting operation: ...
11
votes
2answers
195 views

Dispatch displays rules incorrectly and evaluates when displaying

Bug introduced in 10.0.0 and fixed in 10.0.1 Consider this a = 3; disp = Dispatch[Unevaluated[{a -> 2}]] We see the rule ...
11
votes
3answers
965 views

How to implement a regular grammar?

What is the most simple, elegant way of implementing a rewrite-system defined as: $$ \begin{aligned} \Sigma &= \{a_1, a_2, a_3, ...\} \\ N &= \{A_1, A_2, A_3, ...\} \\ \{\alpha_1 , ...
11
votes
2answers
898 views

Simple problem with Manipulate and Plot

Would anyone have an idea why the following doesn't work: rule = {z -> x^2 + 2 x + y}; Manipulate[ Plot[z /. rule, {x, 0, 10}], {{y, 2, "y"}, 1, 5} ] But ...
11
votes
3answers
665 views

How to properly project a Graphics object consisting of line primitives

My problem starts from attempts at depicting overlapping lines of different thickness, i.e. ...
10
votes
9answers
1k views

How can a power of 0 or 1 be replaced?

Consider this given example for ReplaceAll 1 + x^2 + x^4 /. x^p_ -> f[p] This returns ...
10
votes
3answers
375 views

substitution rules excluding subscripted variables

Suppose I have an expression containing p,Subscript[p,1],Subscript[p,2],etc. I want to ...
10
votes
3answers
349 views

How to replace the first occurance in an expression instead of replacing all?

Is there a function that replaces the first occurance of the expression instead of replacing all? For example, if I have HoldForm[x + 2 + 4 + x] /. x -> 4, is ...
10
votes
2answers
271 views

How to extract a specific element from EXIF photographic metadata?

It's now possible to import photographs into Mathematica and import the EXIF data at the same time: i = Import["ExampleData/coneflower.jpg", "ImageWithExif"] ...
10
votes
1answer
259 views

Is there a programmatic equivalent of Edit > Find…?

Most things that can be done via the front-end interface in Mathematica can also be accomplished by some function. Is that the case for find-and-replacing? That is, is there some code I could execute ...
9
votes
2answers
498 views

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 ...
9
votes
3answers
1k views

Replace expressions with symbols

First of all: I'm new to Mathematica, so I would appreciate it if the answers are quite complete. I have the result of calculation that is expressed in $\sin$ and $\cos$. Now, all of these can be ...
9
votes
4answers
227 views

Leave expression tree formatting the same when a replacement rule is applied

If I type e1 := 3 x + 2 (1 + y) z // TreeForm, I get an expression tree. If I then type e1 /. x -> 3, I get another ...
9
votes
1answer
316 views

error when defining a compiled function with ReplacePart

I always have difficulty in writing a non-trivial compiled function. I'm using Mathematica 9. Please see the following code ...
9
votes
1answer
333 views

How can I replace the Greek symbols in an expression with their plain text names?

Suppose I have an expression with Greek symbols in it. How would I convert that expression to another expression where the Greek symbols have been replaces with their names in plain text? I've ...
9
votes
1answer
89 views

Using PatternSequence on its own in ReplaceAll?

Say I have this list: list = {0, 1, 2, 0, 1, 3, 0, 1, 4} and say I want to remove consecutive sequences of 0 and 1. I'd normally go for this: ...
9
votes
1answer
324 views

Performance of Dispatch and lists of Rules

The issue outlined here seems to be no longer present in version 10, if you use a Dispatch table! This because a Dispatch table ...
8
votes
7answers
309 views

Indexed replacement

Is there some equivalence of MapIndexed for rules? Consider a substitution on 3 a + 4 b + 21 c + .... The first integer I want to replace by 1, the second ...
8
votes
5answers
299 views

Select a particular rules out of a list

rule = {beta -> 4, alpha -> 2, x -> 4, z -> 2, w -> 0.8} Select[rule, beta] Select[rule, beta &] Select[rule, beta -> _ &] How would I ...
8
votes
2answers
291 views

Unexpected behavior of rule matching a pattern

I am a beginner exploring the world of Mathematica. I expected the following code T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] -> Length[List[b]]} should return ...
8
votes
2answers
222 views

Why does the name of a pattern affect the result of a transformation rule?

I was playing a little dirty, trying to get a template for defining a Curl[] operator. I wrote the following rule, which I knew was going to spit out a few ...
8
votes
6answers
1k views

How to simplify a complicated Sum in terms of power Sums?

For example, I have: $a=\sum _{r=1}^n x_r \left(\left(\sum _{i=1}^n x_i-x_r\right){}^2-\sum _{i=1}^n x_i^2\right)$ ...
8
votes
3answers
256 views

Applying a transformation rule on an Image

I haven't been able to figure out why the following doesn't work: ...
8
votes
2answers
205 views

How do I write a function that can be used in a rule to modify both sides of an equation? [duplicate]

I sometimes need fine grain control over equations in Mathematica in order to help me understand how to solve a problem manually. A greatly simplified example of a session might be something like ...
8
votes
1answer
233 views

Why is `Block` significantly faster than `ReplaceAll` for inputting variable values

Given that the documentation for FindMinimum uses ReplaceAll for its various examples of what to do with the found solution to ...
8
votes
2answers
247 views

Replacing product expressions - named vs. unnamed pattern?

Suppose I have an expression of the form a b c d + x y z The FullForm of this is ...
8
votes
1answer
238 views

Is it possible to specify a context-sensitive, “depth-agnostic” rewrite rule?

I'm using the term "depth-agnostic" in this post to describe structural patterns featuring a "target" sub-pattern that can occur "at any depth" relative to one or more "context" sub-patterns. As a ...