Reputation: 281
I know how to solve a simple ode using Euler but confused with putting initial values and solving them
if I have two ODE
dx1/dt=x1*t+x2
dx2/dt=2*x1-x2*t
now I have been given initial values/guess
x1,0=1
x2,0=2
delta(t)=0.0001h
and I need to evaluate this ODE using IVP Euler from t=0 to t=2hr
Upvotes: 0
Views: 190
Reputation: 131
The other person's answer was a god attempt, but was not correct, due to mixing up x's and y's, and because tspan was incorrectly defined. Here is a solution that works.
tspan=[0;2];
x0 = [1; 2];
[t, x] = ode45(@(t,x) [t*x(1) + x(2); 2*x(1) - t*x(2)], tspan, x0);
plot(t,x); legend('x1','x2');
tspan=[start time; end time].
*x0=*vector of initial conditions.
[t, x]=ode45(...)
This calls the ordinary differential equation solver which uses 4th and 5th order Runge-Kutta algorithm. ode45() returns t=vector of times, and x=array of x values at those times. A function definition is passed to ode45. This function of x and t which is passed to ode45() must return a vector whose elements are [dx1/dt; dx2/dt]. You can see from the code that the formulas in the function do in fact match the formulas for the derivatives which were specified. The timespan and the initial condition are also passed. The step size is determined automatically and variably across the interval, in order to achieve the (default) accuracy requirement. The code above produces the plot below.
This solution does not do exactly what the original post requested: it does not use the Euler method and it does not have a step size of 0.001. However, it does work, and it is better than Euler, in the sense that it achieves high accuracy with fewer function evaluations. This is possible because it basically does a 4th order Taylor series approximation at each time step, so it can take big steps and still be accurate. The average time step in this solution is 0.055, versus the 0.001 which was requested in the original post.
Here is code that does exactly what the OP requested: the Euler solution with dt=0.001.
dt=.001; t=0:dt:2;
x=zeros(2,length(t));
x(:,1)=[1;2];
for i=2:length(t), x(:,i)=x(:,i-1)+dt*[t(i-1)*x(1,i-1) + x(2,i-1); 2*x(1,i-1) - t(i-1)*x(2,i-1)]; end
plot(t,x); legend('x1','x2');
Line 1 above sets up dt and the time vector t. Lines 2,3 initialze the x matrix and define initial conditions. Line 4 is a for loop that uses the Euler method to solve the ODEs. Line 5 plots the results. The plot is very similar to the plot from ode45(), above.
Upvotes: 1
Reputation: 281
As time is from 0 to 2hr with step of 0.0001hr we can have our tspan
Initial Values given to be (1,2)
we can use ode45 function of matlab to solve it
and finally we can plot the value
tspan = 0:0.0001:2; % simulation time and step size
x0 = [1; 2]; % initial condition
[t, y] = ode45(@(t,y) [t*x(1) + x(2); 2*x(1) - t*x(2)], tspan, x0);
plot(t, y)
Upvotes: 0