MATLAB: Compare results of different step size using Euler’s method

euler's method

x1=zeros(10000,1);
x2=zeros(10000,1);
x3=zeros(10000,1);
Time=zeros(10000,1);
for i=1:10001
t=(i-1)*0.0005;
Time(i)=t;
if t==0
x1(i)=0;
x2(i)=0;
x3(i)=2;
else
x1(i)=x1(i-1)+x2(i-1)*0.0005;
x3(i-1)=2-9*sin(x1(i-1))-x2(i-1);
x2(i)=x2(i-1)+x3(i-1)*0.0005;
end
Xa=x1*180/pi;
plot(Time,Xa,'red')
I can get the plot for one time interval but I want to get it for different time intervals such as at 0.001, 0.01,0.1 and also compare the results on the same plot. how do i do this? please help??

Best Answer

I have made a few tweaks to your code and it will now allow you to alter one parameter value (the time step size) and produce a new approximation that will be added to your previous plot.
clear all
h = 0.00001;
x1=zeros(round(5/h),1);
x2=zeros(round(5/h),1);
x3=zeros(round(5/h),1);
Time=zeros(round(5/h),1);
for i=1:(5/h)+1
t=(i-1)*h;
Time(i)=t;
if t==0
x1(i)=0;
x2(i)=0;
x3(i)=2;
else
x1(i)=x1(i-1)+x2(i-1)*h;
x3(i-1)=2-9*sin(x1(i-1))-x2(i-1);
x2(i)=x2(i-1)+x3(i-1)*h;
end
end
Xa=x1*180/pi;
hold on
plot(Time,Xa)
Here h is your time step and I have just modified everything else to produce the correct length arrays for storing the results. I also took out the 'red' from your plotting command so that each approximation will automatically plot in a different colour.