Question

I have a function f(x,t) and I'd like to plot the function of the solution x(t) of f(x(t),t)=0 using Mathematica. How can I do it?

Mathematica is often quite different to other programming languages I can use. Normally, I would try something looking like:

Create arrays X, T

For t in T do
   solve (numerically) f(x,t)=0, append the solution to X

Plot X

However, I don't know really well how to use loops in Mathematica yet, and the same for arrays, so I'm having serious problems doing this.

Is there some rapid, direct way of solving this problem with Mathematica? If not, could somebody please help me out with this?

Also, does anybody have a better title for the question?


Edit: Following the suggestion of @LutzL, I would try something like the following:

Table[FindRoot[f[x,t]==0,{x,x_0}],{t,start,stop,step}]

Would this work correctly?

I still have a problem, because my function f(x,t) is highly nonlinear, and thus i would like to input a good starting point for every t. Specifically, I know the solution for t=0 and I would like to use for time step t_{n+1} the solution for t_n. Is there a way to do this?


Edit 2: I solved the problem the following way:

tmax = 10; nsteps = 100*tmax;
thrust = {v/2 - g}; angle = {Pi/2};
For[i = 1, i <= nsteps, i++, 
  sol = {thr, \[Theta]} /. 
    FindRoot[{eq1[i*tmax/nsteps], 
      eq2[i*tmax/nsteps]}, {{thr, Last[thrust]}, {\[Theta], 
       Last[angle]}}]; AppendTo[thrust, sol[[1]]]; 
  AppendTo[angle, sol[[2]]]];
ListPlot[Table[{i*tmax/nsteps, thrust[[i + 1]]}, {i, 0, nsteps}]]
ListPlot[Table[{i*tmax/nsteps, angle[[i + 1]]/Pi}, {i, 0, nsteps}]]

where eq1 and eq2 are my equations and thrust and angle are the solutions

Was it helpful?

Solution

A way to do it would be to create a list and then to plot it.

You have x(0) and you want x(t) for t>0. You can use the expression Szabolcs provides:

root(t_NumericQ, x0_):= Module[{z}, z = z /. FindRoot[f[z, t] == 0, {z, x0}]]

And then you compute and plot a list.

list[tin_, tend_, tstep_, x0_] := Module[{z = x0, t = tin}, lis = {}; 
While[t < tend, z = root[t, z]; lis = Append[lis, {t, z}]; t = t + tstep; ];
ListPlot[lis]]

Or you can change the last line for a x=Interpolation[lis] and x[t] will be an interpolation function for the solution x(t)

Moreover you can test whether other solutions for x(t) are possible replacing root[t,z] for RandomReal[{x_1,x_2}] where x_1and x_2 are in the range of the x space you want to explore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top