Need help with MATLAB code Fuction file euler m is given bel
Need help with MATLAB code.
Fuction file euler. m is given below.
........................................................................................................................................................................
Modify the M-file euler.m to implement the algorithm for Improved Euler. Call the new file impeuler.m (include the file in your report). Test your code for the ODE y\'= 3y, y(0) = 2. First enter the function f(t, y) = 3y as anonymous function and then enter the following:
>> [t5,y5] = impeuler(f,[0,.5],2,5); % use @f if defined in separate function
 >> [t5,y5]
ans = 0 2.0000
 0.1000 2.6900
 0.2000 3.6181
 0.3000 4.8663
 0.4000 6.5451
 0.5000 8.8032
Compare your output with the one above. Note that the improved Euler approximation with 5 steps is already more accurate than the Euler approximation with 50 steps! (hence the “improved”)
Solution
clc
 clear all
 %yn means value of y solved numerical methods
 f=@(t,y) 3*y;
 yn(1)= 2; %initial value matlab index reads from 1
 t0=0;
 tf=0.5;
 h=0.1; %steplength
 tspan=t0:h:tf;
 N=tf/h+1;   % +1 is since t tvalue starts from 0
for n=1:N-1
   
     %improved Euler method %y(n+1)=y(n)+h/2*(f(t(i),y(i))+f(t(i)+h,y(i)+h*f(t(i),y(i)))
     yn(n+1)=yn(n)+h/2*(f(tspan(n),yn(n))+ 3*(yn(n)+h*f(tspan(n),yn(n))));
     %In the aboveline we have to write 3*y f(t(i)+h,y(i)+h*f(t(i),y(i))) in place
     %since yn matrix size & it changes for every iteration
 
 end
 t= tspan\'
 y = yn\'    % change t and y from row to column vectors
output
t =
         0
     0.1000
     0.2000
     0.3000
     0.4000
     0.5000
 y =
    2.0000
     2.6900
     3.6181
     4.8663
     6.5451
     8.8032


