2
$\begingroup$

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]
$\endgroup$
1
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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 /@).

$\endgroup$
  • $\begingroup$ But if the function is large and I can not change y with #, what to do in that case? Thank anyway bill s. $\endgroup$ – Pipe May 25 '13 at 14:18
  • $\begingroup$ 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. $\endgroup$ – bill s May 25 '13 at 14:21
3
$\begingroup$

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}}
 ]
$\endgroup$
  • 1
    $\begingroup$ This is so much more readable. $\endgroup$ – Sasha May 25 '13 at 14:23
  • $\begingroup$ Thank you Sjoerd C. de Vries. It is working with Table. $\endgroup$ – Pipe May 25 '13 at 14:30
  • $\begingroup$ @Sasha, thankfully, Table[] can now operate in a foreach()-like fashion. Old-timers would have used bill's method, tho. $\endgroup$ – J. M. will be back soon May 25 '13 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.