Asked by Riyadh Salim
on 11 Nov 2019

%task4

function adaptive

close all;

y = [0:0]; T = [0];

h = 0.001;

t = 0; i = 1;

err = 1e-3;

while t < 0.5

e = 1;

%h = 0.01;

while (e > err)

y_1 = y(:,i) + h * f(t, y(:,i));

y_2 = y(:,i) + h/2 * f(t, y(:,i));

y_2 = y_2 + h/2 * f(t+h/2, y_2);

e = 2^1*(norm(y_2 - y_1))/(2^1-1);

if (e > err)

h = 0.9 * h*(err*(2^1-1)/(2^1*(norm(y_2-y_1))));

end

end

y(:,i+1) = y_2;

t = t + h; i = i + 1;

T(i) = t;

if (e < 0.5 * err)

h = h*2;

end

end

end

function euler(i, h, t, ye)

ye(i+1) = ye(i) + h*( f( t(i), ye(i) ) );

end

function impli(i, h, t, y_i)

y_i(i)= yi(i) + h*( f( t(i), yi(i) ) );

yi(i+1)=yi(i) + h*(f(t(i+1),y_i(i)));

end

function Heuns(i, h, t, yh)

yh(i+1) = yh(i)+ h/2 * (f(t(i),yh(i)) + f(t(i+1),(yh(i)+ h*f(t(i),yh(i)))));

end

function RK4(i, h, t, yrk)

k1 = f(t(i), yrk(i));

k2 = f(t(i) + h/2, yrk(i) + h/2*k1);

k3 = f(t(i) + h/2, yrk(i) + h/2*k2);

k4 = f(t(i) + h, yrk(i) + h*k3);

yrk(i+1) = yrk(i) + h/6*(k1 + 2*k2 + 2*k3 + k4);

end

%plot(t,ye, 'b');

%figure;

%plot(t, yi, 'r');

%figure;

%plot(t, yh, 'g');

%figure;

%plot(t, yrk, 'y');

%figure;

plot(t, ye, 'b',t, yi, 'r', t, yh, 'g', t, yrk, 'y',x,Yx);

legend('euler','impli','Heuns','RK4','Real')

%plot(t, ye)

function dy=f(t,y)

d = 10;

dy = -d*(y-(cos(t)));

end

Answer by James Tursa
on 11 Nov 2019

Edited by James Tursa
on 11 Nov 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## darova (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/490438-can-someone-help-me-to-solve-this-error-this-statement-is-not-inside-any-function-it-follows-the#comment_766094

Sign in to comment.