4
$\begingroup$

I am trying to do a numerical integration in Mathematica for a basic spring problem. In short, I calculate in loop and save two list of numbers (values of times and positions) and after loop, I want to draw results, with X-axis being a time and Y-axis being a position. Can you help me how to plot this graph when using Range[] to save numbers?

I am also open to recommendations for improvement of code, how would it be more optimal to save this kind of data, would you recommend me using Array[], Table[] or Range[]?

Thanks.

 (* Initial Conditions*)
x0=1;
v0=0;
t0=0;
t=2*Pi;

(*Parameters*)
k=1;
m=1;

h=.1;    (*Step size *)
n = IntegerPart[(t-t0)/h];(* Number of steps *)

(*Miscellenous For Drawing*)
tList = Range[n+1];
tList[[1]]=t0;
xList  = Range[n+1];
xList[[1]]=x0;
vList= Range[n+1];
vList[[1]]=v0;
x=x0;
v=v0;

For[i = 1, i <= n, i++,
vdot= -( k*x)/m;  (* Linear Momentum Balance Equation*)
x = x + v*h;      (* Euler's Method *)
v = v + vdot*h;   (* Euler's Method *)
tList[[i+1]]=i*h;
xList[[i+1]]=x;
vList[[i+1]]=v;
]

Plot[tList,xList] (*???Basically it does not work so I need help with this line*)
$\endgroup$

1 Answer 1

4
$\begingroup$

You are pretty close.
You can combine your two lists with txList = Transpose[{tList, xList}]
And then do ListPlot[txList]
enter image description here

Nothing wrong with what you're doing but you don't need to initialize arrays in Mathematica. So for example you can do:

(*Initial Conditions*)
x0 = 1;
v0 = 0;
t0 = 0;
t = 2*Pi;

(*Parameters*)
k = 1;
m = 1;

h = .1;(*Step size*)
n = IntegerPart[(t - t0)/h];(*Number of steps*)
(*Miscellenous For Drawing*)
tList = {t0};
xList = {x0};
vList = {v0};
x = x0;
v = v0;

For[i = 1, i <= n, i++, 
  vdot = -(k*x)/m;(*Linear Momentum Balance Equation*)
  x = x + v*h;(*Euler's Method*)
  v = v + vdot*h;(*Euler's Method*)
  AppendTo[tList, i*h];
  AppendTo[xList, x];
  AppendTo[vList, v]];

txList = Transpose[{tList, xList}];
ListPlot[txList]
$\endgroup$

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.