I am using euler's method to solve a differential equation, but when I run the code it doesn't plot.

조회 수: 2 (최근 30일)
Hi, I am using Euler's method to solve the differential equation dv/dt, but when I run the code it doesn't plot andI don't get an error.
Any help would be greatly appreciated. Thanks
%Eulers method
t0=0; %start time
t1= 500; %finish time
dt = 100000; %large timestep to avoid errors
n = (t1-t0)/dt +1; %Number of nodes
t = linspace(t0,t1,n);%Time array
n_rou = round(n); %rounds n to an integer for y_euler to work
v_euler = zeros(n_rou,1); %create an empty array
v_euler(1) = 1; %initial value as v(0)=1
dvdt = @(v,t) -2.4*v(t)^2 - v(t)^3-4*v(t)+7.4 ; %anonymous function for dv/dt
for i = 1:n-1
f = dvdt(v_euler(i),t(i)); %Evaluate f=dy/dt at i
v_euler(i+1) = v_euler(i) + dt*f; % Evaluate y at i+1
end
plot(t,v_euler)

채택된 답변

James Tursa
James Tursa 2022년 1월 13일
Take a look at these lines:
t0=0; %start time
t1= 500; %finish time
dt = 100000;
Your stepsize is much larger than the total time! You need to make the stepsize reasonably small given the total time and derivative function involved.
  댓글 수: 3
Rashmika Undu
Rashmika Undu 2022년 1월 13일
Yes thanks @John D'Errico, I was thinking of a large number of timesteps so the small dt makes sense.
Now when I run the code I get this error " Array indices must be positive integers or
logical values." For these two lines:
dvdt = @(v,t) -2.4*v(t)^2 - v(t)^3-4*v(t)+7.4 ; %anonymous function for dv/dt
f = dvdt(v_euler(i),t(i)); %Evaluate f=dy/dt at i
James Tursa
James Tursa 2022년 1월 13일
Assuming v(t) is meant to be "velocity at time t", you should just drop the (t) part since what is passed in for v is at the current time:
dvdt = @(v,t) -2.4*v^2 - v^3-4*v+7.4

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by