Vector ODE using forward Euler method

조회 수: 10 (최근 30일)
Liam Quiros Edmunds
Liam Quiros Edmunds 2021년 1월 10일
답변: James Tursa 2021년 1월 10일
Having trouble defining the following vector ode in matlab.
I have written the following for the right hand side function for suitable use in ode45. The system models a projectile with position and velocity vectors (x(t), y(t)) and (u(t), v(t)) at time t with parameters g and mu for gravity and air resistance.
function dydt = rhs_1(t, y, g, mu)
dxdt1 = u;
dydt2 = v;
dudt3 = -mu.*y(1).*sqrt(y(1).^2+y(2).^2);
dvdt4 = -g-mu.*y(2).*sqrt(y(1).^2+y(2).^2);
dydt = [dxdt1, dydt2, dudt3, dvdt4];
end
And when I run the following;
[t,y,g,mu]=ode45(@rhs_1,[0 100],[0.1; 0], 9.8, 0.5);
plot(t,y,g,mu(:,1),'r.-',t,y(:,2),'g.-','LineWidth',2,'MarkerSize',10);
I get the following error messages;
Unrecognized function or variable 'u'.
Error in rhs_1 (line 2)
dxdt1 = u;
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in runode (line 1)
[t,y,g,mu]=ode45(@rhs_1,[0 100],[0.1; 0], 9.8, 0.5);
Apologies if this is trivial, I am new to Matlab. Any help is greatly appreciated. Thank you!

답변 (2개)

Jan
Jan 2021년 1월 10일
편집: Jan 2021년 1월 10일
You have replaced the "x" of the formula by "y(1)", the "y" by "y(2)". Now you have to replace "u" by "y(3)" also and "v" by "y(4)":
function dydt = rhs_1(t, y, g, mu)
dxdt1 = y(3); % instead of u
dydt2 = y(4); % instead of v
dudt3 = -mu .* y(3) .* sqrt(y(3).^2 + y(4).^2); % y(1) -> y(3), y(2) -> y(4)
dvdt4 = -g - mu .* y(4) .* sqrt(y(3).^2 + y(4).^2);
dydt = [dxdt1, dydt2, dudt3, dvdt4];
end

James Tursa
James Tursa 2021년 1월 10일
Also your main code should look something like this:
g = 9.8;
mu = 0.5;
[t,y]=ode45(@(t,y)rhs_1(t,y,g,mu),[0 100],[0.1; 0]);
Then, depending on how you want your plotting, something like this:
plot(y(:,1),y(:,2));
or
plot(t,y(:,1),t,y(:,2));

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by