How to plot the y and t?

1 view (last 30 days)
ken
ken on 9 Apr 2022
Answered: KSSV on 9 Apr 2022
a = 0;
b = 10;
h = 10^-3;
N = (b-a)/h;
alpha = 1;
f = @(x,y) 1/y^3;
function [y,t] = rk4(f,a,b,alpha,N)
t = [];
y = [];
y0 = alpha;
for i = 1:N
t_i = a+(i-1)*h;
t = [t t_i];
y = [y y0];
k1 = f(t_i, y0);
k2 = f(t_i + h/2, y0+h/2 * k1);
k3 = f(t_i + h/2, y0+h/2 * k2);
k4 = f(t_i + h, y0+h * k3);
y_ = y0 + h / 6 * (k1+2*k2+2*k3+k4);
y0 = y_;
end
y = [y y0];
t = [t a+N*h];
end

Accepted Answer

KSSV
KSSV on 9 Apr 2022
You need to call the function. Provide the input and call the function. There is small typo in your function; it seems the input should be h and not b.
a = 0;
b = 10;
h = 10^-3;
N = (b-a)/h;
alpha = 1;
f = @(x,y) 1/y^3;
[y,t] = rk4(f,a,h,alpha,N) ;
plot(t,y)
function [y,t] = rk4(f,a,h,alpha,N)
t = [];
y = [];
y0 = alpha;
for i = 1:N
t_i = a+(i-1)*h;
t = [t t_i];
y = [y y0];
k1 = f(t_i, y0);
k2 = f(t_i + h/2, y0+h/2 * k1);
k3 = f(t_i + h/2, y0+h/2 * k2);
k4 = f(t_i + h, y0+h * k3);
y_ = y0 + h / 6 * (k1+2*k2+2*k3+k4);
y0 = y_;
end
y = [y y0];
t = [t a+N*h];
end

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!