How do I alter myEuler.m to calculate M and plot the solution?

1 view (last 30 days)
Hi, I am trying to complete a Euler's approximation problem:
How do I calculate M and plot the solution?
h=1 for the IVP: y'=0.1y over [0,5] with y(0)=1000. Given the script:
function [ E] = MyEuler(f,a,b,ya,M) %Input: f is the function entered as a string 'f', see myfunc.m % a left endpoint % b right endpoint % ya initial condition y(a)=y_0 % M number of partitions, M+1 number of points %Output: E solution {t,y(t)}
h=(b-a)/M; T=zeros(1,M+1); Y=zeros(1,M+1);
T=a:h:b; Y(1)=ya;
for j=1:M Y(j+1)=Y(j) + h*feval(f,T(j),Y(j)) end
E=[T' Y'] plot(T,Y,'r:')
end

Answers (1)

Geoff Hayes
Geoff Hayes on 7 Oct 2014
Edited: Geoff Hayes on 7 Oct 2014
Summer - if you want the script to calculate M rather than passing it in as a variable, then you will have to replace it with the step size h and just rearrange the calculation for h to
M = ceil((b-a)/h);
In your case, with the step size of h equal to 1, a equal to 0, and b equal to 5, then M would become 5. (You may want to reconsider renaming this variable from M to n because that seems to be more common in the literature.)
Your call to plot seems correct, so I don't think that there is anything to change there. Putting all the above together would give the following
function [E] = MyEuler(f,a,b,ya,h)
n=(b-a)/h;
T=linspace(a,b,n+1);
Y=zeros(1,n+1);
Y(1)=ya;
for k=1:n
Y(k+1)=Y(k) + h*feval(f,T(k),Y(k));
end
E=[T' Y'] ;
plot(T,Y,'r:');
end
Note that I replaced the index j with k since both i and j are also used representations of the imaginary number (so it is good practice to avoid using either as indices in loops).
Note also the use of linspace which will create a vector of n+1 linearly spaced numbers from a to b.

Tags

Community Treasure Hunt

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

Start Hunting!