I am using mathematica's Nsolve to solve a polynomial. When solved, Nsolve traditionally gives solutions like this:
{{x -> 1}, {x -> 2}, {x -> 3},{x -> 4}}
However, I need to transform this output into a list of numbers, so it looks like:
{1, 2, 3, 4}
How can I do this? There must be a simple way.
You have a list {{x -> 1}, {x -> 2}, {x -> 3},{x -> 4}}
and you want to do the same thing to each item in that list, you want to replace the {x -> n}
with n
.
This is a very common thing to want to do in Mathematica. There is a function Map
which accepts a function and a list and does that function to each item in the list. You can look up Map
in the help pages and try to make sense of it.
Your list has Rule
's in it. So what you have is {{Rule[x,1]}, {Rule[x,2]}, {Rule[x,3]},{Rule[x,4]}}
, which Mathematica abbreviates into {x -> 1}
, etc. You can look up Rule
in the help system and try to make sense of it.
Let's look at one way of doing what you want
sol = {{x -> 1}, {x -> 2}, {x -> 3}, {x -> 4}};
f[r_] := ReplaceAll[x, r];
Map[f, sol]
That defines a function f
which uses the ReplaceAll
function with x
and an individual Rule
to replace all the x
's in x
, and there is only one, with the value from that rule. And then the Map
does this over and over until it has processed all the items in your list. and the result is {1, 2, 3, 4}
which is what you wanted.
Now the culture of Mathematica is that you try to abbreviate everything, you always try to use a handful of punctuation characters instead of using the name of a function. That can be pretty difficult for a new user to understand. Here is a different way a Mathematica user might write that instead.
x/.#&/@{{x -> 1}, {x -> 2}, {x -> 3}, {x -> 4}}
and that will give you the same result. You can look up /.
and #
and &
and /@
in the help system and try to make sense of those.
There are almost always a dozen different ways of accomplishing anything in Mathematica. at least several of which are almost completely incomprehensible. If you can, choose a way of doing things that you think you understand and can remember and use without making too many mistakes. But this routinely seems to become a contest to see who can accomplish something using a few less characters or who can make this run in a few less seconds.