# How to calculate solution for each variable automatically

Here I have one problem how to calculate x for each y. In this form code doesn't work

     y = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6,0.7};

NSolve[-y*16 x^3 - y^2*25 x^2 + 5 == 0, x]

-

I, too, would probably do it bill's way, but for variety, here's another way.

y0 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7};

SetAttributes[solve, Listable];
solve[y_] := solve[y] = NSolve[-y*16 x^3 - y^2*25 x^2 + 5 == 0, x];

solve[y0]


Omit the memoization (solve[y] =) if you don't want to save the solutions. But try

?solve


and you'll see that the solution for each value in y0 is stored in solve[0.1], solve[0.2], etc.

-

You can use "pure functions" like this:

y = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7};
NSolve[-#*16 x^3 - #^2*25 x^2 + 5 == 0, x] & /@ y


This calculates the NSolve for each of the ys. You can think of the Slot (the symbol # and its companion &) as a variable that gets filled in by all the values after the Map (represented by the /@).

-
But if the function is large and I can not change y with #, what to do in that case? Thank anyway bill s. –  Pipe May 25 '13 at 14:18
If you give an example of what you wish to do, we can probably help. There are many ways to structure your code. The best way depends on details of how the functions are defined. –  bill s May 25 '13 at 14:21

In addition to bill's version, which is probably what I'd do as well, another reasonable possibility would be:

Table[
NSolve[-y*16 x^3 - y^2*25 x^2 + 5 == 0, x],
{y, {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}}
]

-
This is so much more readable. –  Sasha May 25 '13 at 14:23
Thank you Sjoerd C. de Vries. It is working with Table. –  Pipe May 25 '13 at 14:30
@Sasha, thankfully, Table[] can now operate in a foreach()-like fashion. Old-timers would have used bill's method, tho. –  Guess who it is. May 25 '13 at 15:09