Converting Euler ODE to the MATLAB code
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Haider Ali
le 14 Sep 2021
Commenté : Haider Ali
le 14 Sep 2021
Hey Everyone!
I have a question related to the Euler Method implementation. I have the following function:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/738419/image.png)
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.
0 commentaires
Réponse acceptée
Fabio Freschi
le 14 Sep 2021
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Ordinary Differential Equations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!