Eulers method range issue question

1 view (last 30 days)
Evan Kardos
Evan Kardos on 28 Jul 2019
Edited: Jim Riggs on 1 Aug 2019
Hello All!
I'm working on a homework assignment where we code Eulers method, the issue I'm having is that my code seems to stop at t=2, which means it's only estimating y(2), I need my code to stop when t = 4, meaning it's estimating y(4). Here is the question I'm trying to solve, this is just part A that i'm asking about so far.
rsz_capture.jpg
So here is my function I've written for Eulers:
function [t,y] = myEuler(f,range,ic,h)
%input f is the RHS of the ODE
%input range is a vector [initial time, final time]
%input ic is an initial condition
%input h is a step size
%output t is an array containing the times that correspond to the approximations in y
%output y is an array containing approximations to the solution of the IVP
%set up the time array
t = (range(1):h:range(2))';
%preallocate for y array
y = zeros(length(t),1);
y(1) = ic; %w1 = y1
for i = 2:length(y)
y(i) = y(i-1) + h*f(t(i-1) , y(i-1)); %This is wi+1 in my notes
end
And then to call this function and enter my inputs I have this code:
format long
f = @(t,y) 6*t-3*y+5;
R = [1:16];
h = 0.2;
ic = 4;
[t,y] = myEuler(f,R,ic,h)
Doing this only gives me this range and corresponding y values:
t =
1.000000000000000
1.200000000000000
1.400000000000000
1.600000000000000
1.800000000000000
2.000000000000000
y =
4.000000000000000
3.800000000000000
3.960000000000000
4.264000000000000
4.625600000000000
5.010240000000000
Thank you in advance for any help!!

Answers (1)

Jim Riggs
Jim Riggs on 1 Aug 2019
Edited: Jim Riggs on 1 Aug 2019
In your code, you specify:
R=[1:16];
h=0.2;
ic=4;
Then you call the function
[t,y]=myEuler(f,R,ic,h)
Inside myEuler, it computes the range of t as R(1):h:R(2)
Now, your assignment of R=[1:16] results in R = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
So t is evaluated from R(1) to R(2) which is 1 to 2.
It looks like what yo want is R=[1,4] and ic = 1.

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!