Hi, I have to solve a an ODE with the Euler method for two separate step sizes and have to place them on same graph. I'm very confused on how to do this... Please help me...
y'=1/y; Initial Condition y(0) = 1;
I have to use Euler method to solve for y(1) for step size deltat = 0.1 and also deltat = 0.01
This is as far as I got and I'm just completely stuck.....
t0=0; t1=1; dt=0.1; %define time range and step size
y0=1; %initial condition
t=t0:dt:t1;
y=zeros(size(t,1), size(t,2))
for i=1: ((t1-t0)/dt)
y(i+1)=y(i)+1/y(i)*dt
end

댓글 수: 4

Note: your line
for i=1: ((t1-t0)/dt)
risks round-off errors in the calculation of the number of elements. You would be better using
for i = 1 : length(t)
Also note that your y matrix is created as 2D but you are only using a single index of it. In this particular case, using length(t) would work, but more generally you would use
y = zeros(size(t));
for i = 1 : numel(y)
I would also recommend you rethink your termination condition: is your output intended to be one element for each time, or is the output intended to be one element for each time, plus one final element that is the prediction for the next time? Because you are assigning to y(i+1)...
Jim Riggs
Jim Riggs 2020년 2월 23일
편집: Jim Riggs 2020년 2월 23일
The solution vector is sized to be y=zeros(size(t)), and the looping computes y(i+1), therefore the loop index should be
for i=1:length(t) -1
or
for i=1:numel(y)-1
Keeping vectors y and t the same length is a good idea.
Nasir Holliday
Nasir Holliday 2020년 2월 23일
I'm sorry but I'm not really understanding
t0=0; t1=1; dt=0.1; %define time range and step size
y0=1; %initial condition
t=t0:dt:t1;
y=zeros(size(t));
num_t = length(t);
for i = 1: num_t - 1
y(i+1)=y(i)+1/y(i)*dt
end

댓글을 달려면 로그인하십시오.

답변 (1개)

Pravin Jagtap
Pravin Jagtap 2020년 2월 25일
편집: Pravin Jagtap 2020년 2월 25일

0 개 추천

Hello Nasir,
Refer to the following function which takes ‘dt’ and ‘y0’ as an input argument and returns the ‘y’ as solution for time vector from 0 to 1 with ‘dt’ as timestep (This is just a demonstrative example. You can modify as per your requirements).
function y = EulerMethod(dt, y0)
% Preparing the Time vector from tStart to tEnd
t_Start = 0;
t_End = 1;
t = t_Start:dt:t_End;
% Initialize the solution vector
y = zeros(size(t));
% Impose Initial Condition
y(1) = y0;
% Compute the Solution vector using the Eulers Method
num_t = length(t);
for i = 1: num_t - 1
y(i+1)=y(i)+((1/y(i))*dt);
end
end
Call the above function for different values of ‘dt’ as follows and plot it
% call the function for dt 0.1
y1 = EulerMethod(0.1,1);
% call the function for dt 0.01
y2 = EulerMethod(0.01,1);
% Plot the corresponding solutions
t1 = 0:0.1:1;
plot(t1,y1)
hold on
t2 = 0:0.01:1;
plot(t2,y2)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2020년 2월 22일

편집:

2020년 2월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by