Hi,
You have overlooked the loop iteration and time space. Here is the corrected code:
% improved eulers method for stped size 1
y0 = pi/6;
x0 = 0;
xn = 5;
h = 1; % h = 0.5; % h = 0.25;
dy = @(x,y) cot(y); % dy/dx
y = y0;
x = x0:h:xn;
for ii = 1:numel(x)-1
y(ii+1) = y(ii) + dy(x(ii),y(ii))*h;
end
plot(x,y, 'b-o')
legend('Improved Euler 1')
hold on
% Solve the ODE
f = @(t,y) cot(y);
y0 = pi/6;
t2 = 0:h:5;
[t2,y2] = ode45(f,t2,y0);
plot(t2,y2,'LineWidth',3,'DisplayName','Exact solution');
legend show
%%
Now you can extent the code with other time steps for h= 0.5 and 0.25 by changing the value of h.
Good luck.