MATLAB Answers

My code won't run, related to ode function

2 views (last 30 days)
Dardenella Finegan
Dardenella Finegan on 24 May 2020
Commented: Stephen Cobeldick on 24 May 2020
%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

  0 Comments

Sign in to comment.

Answers (1)

David Goodmanson
David Goodmanson on 24 May 2020
Edited: David Goodmanson on 24 May 2020
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.

Community Treasure Hunt

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

Start Hunting!

Translated by