Message Boards Message Boards

Assign values to an NDSolve inside a For loop

Posted 3 years ago

Hello, I am trying to assign the values of Solve function to an NDSolve inside a For loop. To be more precise: I use Solve to find the values of p as shown in the example and then, I would like to use each value of p to compute the NDSolve function. These are test functions because the originals are too big to post them. The idea remains the same though. The integration seems to stop at step one. Below is what i am trying to do. I have uploaded the script too.

Thank you all in advance

For[i = 1, i < 4, i = i + 1, 
t = p /. Solve[p - 2 i == 0]; 
 s = NDSolve[{y'[x] == t*y[x] Cos[x + y[x]], y[0] == 1},    y, {x, 0, 30}];
 Print@Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All];]
Attachments:
POSTED BY: Agapi Pop
2 Replies
Posted 3 years ago

I cannot thank you enough. Your coding proposal is so elegant. Thank you again!

POSTED BY: Agapi Pop

Hello Agapi Pop,

to make your code run you need to rewrite the second line like so:

t = First[p /. Solve[p - 2 i == 0]];

This is, because here the result of Solve is a List containing one element, and you want that element only.

But - if I may add - a more Mathematica like coding would read:

t = Flatten@Table[p /. Solve[p - 2 i == 0, p], {i, 1, 4}];
s = NDSolveValue[{y'[x] == #*y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}] & /@ t;
Plot[Evaluate@Through[s[x]], {x, 0, 30}, PlotRange -> All]
(* or likewise: *)
Plot[#[x], {x, 0, 30}, PlotRange -> All] & /@ s

enter image description here

POSTED BY: Henrik Schachner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract