% Uses Euler's method to compute numerical solution to the ode % y'=f(t,y) y(a)=alpha a<=t<=b. % Asks user to input a,b,step size h and initial value alpha % Assumes f is evaluated in a separate function file f.m % Plots the result with discrete points. a=0; b=2; h=input('Please enter the step size'); n=ceil((b-a)/h); alpha1=pi/6; alpha2=0; clear t w t=a:h:(a+n*h); w(1,1)=alpha1; w(2,1)=alpha2; for i=1:n k1=h*F2(t(i),w(:,i)); k2=h*F2(t(i)+h/2,w(:,i)+(1/2)*k1); k3=h*F2(t(i)+h/2,w(:,i)+(1/2)*k2); k4=h*F2(t(i+1),w(:,i)+k3); w(:,i+1)=w(:,i)+ (1/6)*(k1+2*k2+2*k3+k4); end hold off plot(t,w(1,:),'*'); %For the example y'=y^2-t^2+1 y(0)=0.5 % here we now plot the true solution alongside the % approximation. %hold on %tvals=0:0.01:1; %plot(tvals,-(2/5)*exp(2*tvals).*cos(tvals)+(1/5)*exp(2*tvals).*sin(tvals));