3
$\begingroup$

I was reading basic help here How to | Combine Two or More Graphics , but I did not get it.

I have simple differential equation and want to change a constant "b" (in this case "damping") and plot all graphs in a single image. Here is the code:

(*Single mass damper system of a rail car *)
(*with 10 mm starting deflection *)
m = 40000;     (* [kg]    *)
k = 1600000; (* [N/m]   *)

for[b=0, b<=160000, b=b+20000,

sol = NDSolve[{
m*x''[t] + b*x'[t] + k*x[t]== 0,
x'[0] == 0,x[0] == 0.01},
x[t], {t, 0, 10}];

Print[Plot[x[t] /. sol, {t, 0, 3}, 
PlotRange -> Full ,
PlotTheme -> {"Grid"},
AxesLabel->{"Time [s]", "Vertical suspension deflection [m]"}, 
PlotLabel->Style["Single mass damper system of a rail car", 12, Bold]]] 
]

Can anyone please help? I'm just missing "hold on" from Matlab here. Thank you in advance.

$\endgroup$
4
  • 4
    $\begingroup$ Trying to use the procedural programming you are used from Matlab usually wont give you a nice solution in mathematica. The more idiomatic Mathematica way is usually shorter and easier. Your problem gets very easy like that: sols=Table[x[t]/.NDSolve[{m*x''[t]+b*x'[t]+k*x[t]==0,x'[0]==0,x[0]==0.01},x[t],{t,0,10}],{b,0,160000,20000}]; Plot[sols,{t,0,3}] $\endgroup$ Jun 27, 2021 at 21:03
  • 2
    $\begingroup$ You should also be aware that for is not the same as For. $\endgroup$ Jun 28, 2021 at 4:06
  • 2
    $\begingroup$ I also recommend looking up ParametricNDSolveValue, which makes is much easier to solve DEs for different parameter values. $\endgroup$ Jun 28, 2021 at 6:47
  • $\begingroup$ Thank you all for the hints! I really appreciate that! $\endgroup$ Jun 28, 2021 at 15:34

1 Answer 1

5
$\begingroup$
Clear["Global`*"];

m = 40000;
k = 1600000;

Your equation can be solved exactly with DSolve

sol = DSolve[{m*x''[t] + b*x'[t] + k*x[t] == 0, x'[0] == 0, x[0] == 1/100}, 
    x[t], t][[1]] // Simplify

enter image description here

Alternatively,

sol2 = sol // ExpToTrig // Simplify

enter image description here

Plotting,

Plot[Evaluate@Table[x[t] /. sol,
   {b, 0, 160000, 20000}], {t, 0, 3},
 PlotTheme -> "Grid",
 Frame -> True,
 FrameLabel -> (Style[#, 12, Bold] & /@
    {"Time [s]", 
     "Vertical suspension deflection [m]"}),
 PlotLabel -> 
  Style["Single mass damper system of a rail car", 12, Bold],
 PlotLegends ->
  LineLegend[Range[0, 160000, 20000],
   LegendLabel -> Style["b =", 12, Bold]]]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you very much! That works perfect! I appreciate your help. $\endgroup$ Jun 28, 2021 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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