Mass spring system: given code unable to run and returning errors

1 次查看(过去 30 天)
I am starting a project that covers modeling a mass spring system in MatLab. In this lab, we've been provided with some initial code to run in a .m file. According to the video instructions for the project, the code should run without any modification or edits. However, when I run the code, numerous errors are returned.
The code:
function LAB08ex1
m = 1; % mass [kg]
k = 4; % spring constant [N/m]
omega0 = sqrt(k/m);
y0 = 0.1; v0 = 0; % initial conditions
[t,Y] = ode45(@f,[0,10],[y0,v0],[],omega0); % solve for 0<t<10
y = Y(:,1); v = Y(:,2); % retrieve y, v from Y
figure(1); plot(t,y,'b+-',t,v,'ro-'); % time series for y and v
grid on
%legend('y(t)','v(t)=y''(t)'); % note the use of '' for '
%figure(2); plot(y,v); % phase plot
%xlabel('y'); ylabel('v=y'''); grid on
%-----------------------------------------
function dYdt = f(t,Y,omega0)
y = Y(1); v = Y(2);
dYdt = [ v ; -omega0^2*y ];
Running this code returns the following errors:
>> LAB08ex1
Index exceeds array bounds.
Error in LAB08ex1>f (line 15)
y = Y(1); v = Y(2);
Error in ode45 (line 273)
k_(:,1)=feval(FUN,x,t);
Error in LAB08ex1 (line 6)
[t,Y] = ode45(@f,[0,10],[y0,v0],[],omega0); % solve for 0<t<10
What is going wrong and how should I fix it?
  1 个评论
Jorian
Jorian 2018-4-7
Update: I was using a different variant of ODE45 than the one that comes built into Matlab. Deleting and using the normal ODE45 results in working code.

请先登录,再进行评论。

采纳的回答

Jim Riggs
Jim Riggs 2018-4-7
The code works just fine for me. Perhaps you have a variable that is ghosting one of your variables. Try clearing the workspace
clear all
  2 个评论
Walter Roberson
Walter Roberson 2018-4-7
The code works for me as well. However, I recommend that you do not rely upon a behavior that has been undocumented since MATLAB R13. I am referring to the behavior of passing in extra parameters to the function by putting them at the end of the list of ode* parameters.
I can guarantee you that using that particular undocumented behavior will fail in some cases, because of internal choices about other undocumented or little documented behavior: there are some options that expect the possibility of additional parameters, and will go ahead and use your "omega0" as data for that option.
You should parameterize your function instead. See http://www.mathworks.com/help/matlab/math/parameterizing-functions.html
Jorian
Jorian 2018-4-7
Thank you. I've cleared the workspace and restarted Matlab before running the code again, but am getting the same errors. Is it possible that we have different toolboxes or versions of Matlab? I'm running Matlab r2018a with the symbolic math toolbox 8.1, if that helps.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Assembly 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by