Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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]
share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

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}}
 ]
share|improve this answer
1  
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. –  J. M. May 25 '13 at 15:09
add comment

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

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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