Converting Euler ODE to the MATLAB code

4 次查看(过去 30 天)
Hey Everyone!
I have a question related to the Euler Method implementation. I have the following function:
(1)
I have written its main function code as:
function y = eulerfunction(func, t, y0)
n = length(t);
y = nan(length(y0), n);
y(:,1) = y0(:);
for k = 1:n-1
h = t(k+1) - t(k);
y(:,k+1) = y(:,k) + h*func(t(k), y(:,k));
end
end
Now I am writing the remaining script.
y0 = [3,0];
h = 0.5;
t = 0;
% I am confused in this line that what to write in these square brackets according to the given equation (1)
f = @(t, y) [ ];
y = eulerfunction(f, t, y0)
Can you please help me to convert that f(t,y) in MATLAB Format? Like what to write in these brackets '[ ]' according to the f (t,y) in above equation (1):
f = @(t, y) [ ];
Any help will be really appreciated! Thanks alot in advance.

采纳的回答

Fabio Freschi
Fabio Freschi 2021-9-14
f is an anonymous function
f = @(t,y)[-2*y(1)+y(2)+15*cos(t); 2*y(1)-y(2)];
note that your script is not correct, since t is the time vector used for the time integration and h is calculated inside the euler function. All in all
% initial value
y0 = [3,0];
% time vector
t = linspace(0,4*pi,100);
% anonymous function
f = @(t,y)[-2*y(1)+y(2)+15*cos(t); 2*y(1)-y(2)];
% solution
y = eulerfunction(f, t, y0);
% plot
figure,plot(t,y);
% your euler method
function y = eulerfunction(func, t, y0)
n = length(t);
y = nan(length(y0), n);
y(:,1) = y0(:);
for k = 1:n-1
h = t(k+1) - t(k);
y(:,k+1) = y(:,k) + h*func(t(k), y(:,k));
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by