My code won't run, related to ode function

조회 수: 1 (최근 30일)
Dardenella Finegan
Dardenella Finegan 2020년 5월 24일
댓글: Stephen23 2021년 5월 14일
%E_as_a_function_of_time
m = 1; % mass [kg]
k = 4; % spring constant [N/m]
c = 1; % friction coefficient [Ns/m]
omega0 = sqrt(k/m); p = c/(2*m);
y0 =0.1; v0 = 0; % initial conditions
[t,Y] = ode45(@f,[0,10],[y0,v0],omega0,[],p); % solve for 0<t<15
y = Y(:,1); v = Y(:,2); % retrieve y, v from Y
figure(1); plot(t,y,'ro-',t,v,'b+-');% time series for y and v
grid on; axis tight;
%---------------------------------------------------
function dYdt = f(t,Y,omega0,p); % function defining the DE
y = Y(1); v = Y(2);
dYdt=[ v ; -omega0^2*y-2*p*v]; % fill-in dv/dt
end

답변 (2개)

David Goodmanson
David Goodmanson 2020년 5월 24일
편집: David Goodmanson 2020년 5월 24일
Hi Dardenella,
try the same thing only with
[t,Y] = ode45(@(t,Y) f(t,Y,omega0,p), [0,10],[y0,v0]); % solve for 0<t<10 [not 15]
Sometimes it's less than obvious where the @'s should go. But the function call has to match the argument list it the function definition.

Poojana mathlab
Poojana mathlab 2021년 5월 14일
%mass [kg] %spring constant
k=4; %spring constant[N/m]
omega0=sqrt(k/m)
x0=0.1; v0=0 %initial conditions
[t,X]=ode45(@f,[0,10],[y0,v0],[],omega0); %solve for 0<t<10
x= X(:,1);v=X(:,2); %retrieve y,v from X
figure(1); plot(t,x,'b+-',t,v,'ro-'); %time series for x and v
%--------------------------------------
function dYdt= f(t,Y,omega0);x=X(1);v=X(2);
dYdt=[v;-omega062*x];end
doesnt work
  댓글 수: 1
Stephen23
Stephen23 2021년 5월 14일
Works perfectly, following the answer and comment above and fixing all of the mismatching variable names:
m=1;%mass [kg]
k=4;%spring constant[N/m]
omega0=sqrt(k/m);
fun = @(t,Y) f(t,Y,omega0);
[t,Y]=ode45(fun,[0,10],[0.1,0]); %solve for 0<t<10
x=Y(:,1);
v=Y(:,2);
plot(t,x,'b+-',t,v,'ro-')
%--------------------------------------
function dYdt = f(t,Y,omega0)
x=Y(1);
v=Y(2);
dYdt=[v;-omega0*x];
end

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

카테고리

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