Message Boards Message Boards

NDSolve with varying parameter using for loop?

GROUPS:

Hello, I have a coupled differential equation and I would like to vary the value k1 between 1000 and 1500 by an increment of 100 using for loop. Can you please help?

m1 = 1;
m2 = 1;
k1 = 1000;
k2 = 1000;
eom1 = m1 x1''[t] + k1 (x1[t] - x2[t]) == 0;
eom2 = m2 x2''[t] + k1 (x2[t] - x1[t]) == 0;
sol = NDSolve[{eom1, eom2, x1[0] == 0, x2[0] == 0, x1'[0] == 1, 
    x2'[0] == 0}, {x1[t], x1'[t], x2[t], x2'[t]}, {t, 0, 5}];
Plot[Evaluate[x1'[t] /. sol], {t, 0, 5}]
POSTED BY: Joeseph A
Answer
15 days ago

Hi Joeseph,

what have you tried? I would have thought that the most obvious way is something like:

Table[
 m1 = 1;
 m2 = 1;
 k1 = loop;
 k2 = 1000;
 eom1 = m1 x1''[t] + k1 (x1[t] - x2[t]) == 0;
 eom2 = m2 x2''[t] + k1 (x2[t] - x1[t]) == 0;
 sol = NDSolve[{eom1, eom2, x1[0] == 0, x2[0] == 0, x1'[0] == 1, x2'[0] == 0}, {x1[t], x1'[t], x2[t], x2'[t]}, {t, 0, 5}];
 Plot[Evaluate[x1'[t] /. sol], {t, 0, 5}, PlotPoints -> 100], 
{loop, 1000, 1500, 100 }]

which seems to work just fine....?

enter image description here

Am I missing the point?

Best wishes,

Marco

POSTED BY: Marco Thiel
Answer
15 days ago

Dear Marco I meant using the for loop inside the NDSolve. It seems fine, but I am kinda wanting to use the for loop within the NDSolve. Thanks.

POSTED BY: Joeseph A
Answer
15 days ago

Dear Joeseph,

the thing is that if you put it in a for loop it calculates but does not display everything. You can generate a list of all the results and append the images to that like so:

m1 = 1;
m2 = 1;
k2 = 1000;
eom1 = m1 x1''[t] + k1 (x1[t] - x2[t]) == 0;
eom2 = m2 x2''[t] + k1 (x2[t] - x1[t]) == 0; results = {}; For[
 k1 = 1000, k1 <= 1500, k1 = k1 + 100, 
 sol = NDSolve[{eom1, eom2, x1[0] == 0, x2[0] == 0, x1'[0] == 1, 
    x2'[0] == 0}, {x1[t], x1'[t], x2[t], x2'[t]}, {t, 0, 5}];
 AppendTo[results, Plot[Evaluate[x1'[t] /. sol], {t, 0, 5}, PlotPoints -> 100]]]

If you then evaluate "results" you obtain he same image as above. This is not elegant though. Have you thought about using the powerful ParametricNDSolve function?

m1 = 1;
m2 = 1;
k2 = 1000;
eom1 = m1 x1''[t] + k1 (x1[t] - x2[t]) == 0;
eom2 = m2 x2''[t] + k1 (x2[t] - x1[t]) == 0; results = {}; sol = 
 ParametricNDSolve[{eom1, eom2, x1[0] == 0, x2[0] == 0, x1'[0] == 1, 
   x2'[0] == 0}, {x1[t], x1'[t], x2[t], x2'[t]}, {t, 0, 5}, {k1}];
Manipulate[Plot[Evaluate[x1'[t][k1] /. sol], {t, 0, 5}, PlotPoints -> 100], {k1,1000, 1500}]

This gives a dynamics interface:

enter image description here

This here for example would give you the list of graphics in steps of 100:

Table[Plot[Evaluate[x1'[t][k1] /. sol], {t, 0, 5}, PlotPoints -> 100], {k1, 1000, 1500, 100}]

Best wishes, Marco

POSTED BY: Marco Thiel
Answer
15 days ago

Group Abstract Group Abstract