In: Computer Science
Write Matlab code that solves (dy/dt)= yt^3 - 1.5y on the interval t= 0 to 2 where y(0) = 1. As well as (dy/dx) = (1+4x)y^.5 on the interval x = 0 to 1 where y(0) = 1 using Matlab functions that solve any ODE using the below methods
Functions need to call:
And return
`Hey,
Note: In case of any queries, just comment in box I would be very happy to assist all your queries
clc
clear all
close all
f=@(t,y) y*t^3-1.5*y;
g=@(x,y) (1+4*x)*y^(0.5);
disp('Equation 1 using heun');
[T,Y]=heun(f,[0,2],1,0.05)
plot(T,Y);
title('Equation 1 plot heun');
disp('Equation 2 using heun');
[X,Y]=heun(g,[0,2],1,0.05)
figure;
plot(X,Y);
title('Equation 2 plot heun');
figure;
disp('Equation 1 using midpoint');
[T,Y]=midpoint(f,[0,2],1,0.05)
plot(T,Y);
title('Equation 1 plot midpoint');
disp('Equation 2 using midpoint');
[X,Y]=midpoint(g,[0,1],1,0.05)
figure;
plot(X,Y);
title('Equation 2 plot midpoint');
function [t,y] = midpoint(f,tspan,ya,h)
a=tspan(1);
b=tspan(2);
n = floor((b - a) / h);
halfh = h / 2;
y(1,:) = ya;
t(1) = a;
for i = 1 : n
t(i+1) = t(i) + h;
z = y(i,:) + halfh * f(t(i),y(i,:));
y(i+1,:) = y(i,:) + h * f(t(i)+halfh,z);
end
end
function [t,y] = heun(f,tspan,ya,h)
a=tspan(1);
b=tspan(2);
n = floor((b - a) / h);
halfh = h / 2;
y(1,:) = ya;
t(1) = a;
for i = 1 : n
t(i+1) = t(i) + h;
g = f(t(i),y(i,:));
z = y(i,:) + h * g;
y(i+1,:) = y(i,:) + halfh * ( g + f(t(i+1),z) );
end
end
Kindly revert for any queries
Thanks.