Mathematica Asked by dpholmes on August 10, 2021
I think I am missing something simple, so I apologize in advance…
I have two lists
{-1 – $epsilon$ + 1/2 $epsilon^2$ x”[0], 1 – $epsilon$ + 1/2 $epsilon^2$ x”[0]}
and
{x”[0]-> -1, x”[0]->1}
I simply want to replace x''[0]
in the first item of the first list with the rule in the first item of the second list, and so on. I have tried using Thread[]
but I must have the wrong syntax.
I am using this in a class demo, so if it is possible to do this in the least Mathematica way possible (please don’t throw things), that would be greatly appreciated 🙂
You can useMapThread
:
list = {-1 - ϵ + 1/2 ϵ^2 x''[0], 1 - ϵ + 1/2 ϵ^ 2 x''[0]};
rules = {x''[0] -> -1, x''[0] -> 1};
MapThread[ReplaceAll, {list, rules}]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
You can also use Inner
as follows:
Inner[ReplaceAll, list, rules, List]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
How to do it with Thread
:
If you use Thread
you need to wrap ReplaceAll[...]
with Unevaluated
to prevent ReplaceAll
being evaluated before Thread
gets to do its job:
Thread[Unevaluated[ReplaceAll[list, rules]]]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
Another way to use Thread
:
ReplaceAll @@@ Thread[{list, rules}]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
Least Mathematica way:
My candidate for doing this in the least Mathematicaesq way in Mathematica is:
For[results = {}; i = 1, i <= 2, i++, AppendTo[results, list[[i]] /. rules[[i]]]]
results
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
Halloween specials:
☺ = # /. #2 & @@@ ({##}[Transpose]) &;
☺[list, rules]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
☺☺ = {# /. #3, #2 /. #4} & @@ (## & @@@ {##}) &;
☺☺[list, rules]
{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}
Correct answer by kglr on August 10, 2021
"The least Mathematica way possible"? Something like this?
lst = {-1 - ϵ + 1/2 ϵ2 x''[0], 1 - ϵ + 1/2 ϵ2 x''[0]};
rules = {x''[0] -> -1, x''[0] -> 1};
Table[ lst[[i]] /. rules[[i]], {i, Length@rules}]
Answered by Markhaim on August 10, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP