# Converting Euler ODE to the MATLAB code

1 view (last 30 days)
Haider Ali on 14 Sep 2021
Commented: Haider Ali on 14 Sep 2021
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 on 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); 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
Haider Ali on 14 Sep 2021
thats perfect! thanks alot for this urgent help.