Numerical solution of differential equations


tulip
01-26-2010, 03:02 PM
My problem is how to plot the exact and the approximated solutions?
This is the MatLab M-file for solving differential equations with Euler's Method.

a=0;
b=1;
y0=-1;
N=10;
fprintf('\n')
disp(' Euler Method ')
disp('__________________________________')
disp('ti f(ti,yi) yi exact error')
disp('__________________________________')
fprintf('\n')
h=(b-a)/N;
y=y0;
fprintf('%4.2f ----------- %12.6f %12.6f %4.2f\n',a,y,y,0)
for i=1:N
t=a+(i-1)*h;
m=f(t,y);
y=y+h*m;
t=t+h;
g=exp(-t)+2*t-2; (exact solution)
if (g~='N')
err=abs(g-y);
fprintf('%4.2f %12.6f %12.6f %12.6f %8.2e\n',t,m,y,g,err)
else
fprintf('%4.2f %12.6f %12.6f\n',t,m,y)
end
end

michielm
03-22-2010, 07:17 AM
your approximate solution is y right?!

Then you can just store the value in a vector every time step.
Inside your loop put:
yp(i)=y
gp(i)=g
tp(i)=t

Then at the end of your file put:

plot(tp,y,tp,g,'+')
legend('Approximate solution', 'Real solution')
xlabel 'Time'
ylabel 'Function value'