# Index exceeds the number of array elements (2)

5 views (last 30 days)
Nejc Jansa on 13 May 2021
Commented: Nejc Jansa on 13 May 2021
I am doing homework for school where i have to get a spring oscillation graph. The program keeps reporting an error to me and I don’t know what could be wrong.
function [t,Y]=naloga6
g=9.8;
m=1;
k1=20;
k2=30;
tr=0.4;
L=2;
alfa=pi/6;
tstart=0;
tfinal=10;
y0 = [L*cos(alfa);L*sin(alfa)];
[t,Y] = ode23(@desne_strani, [tstart tfinal],y0,[],g,m,k1,k2,alfa,tr);
figure(16);
% hold on
% plot3(Y(:,1),Y(:,2),Y(:,3),'r')
dimen= [min(Y(:,1)) max(Y(:,1)) min(Y(:,2)) max(Y(:,2))+0.5 ];
casi=tstart:0.01:tfinal;
Yfilm=interp1(t,Y,casi);
for i=1:size(casi,2)
plot(Yfilm(i,1),Yfilm(i,2),'ro')
axis(dimen)
Film(i)=getframe;
end
function dydt = desne_strani(t,y,g,m,k1,k2,alfa,tr)
dydt = [
y(4)
0
y(6)
-((k1*y(1)*cos(alfa))/m)-((k2*y(1)*cos(alfa))/m)-(tr*g*cos(alfa))
0
-((k1*y(3)*sin(alfa))/m)-((k2*y(3)*sin(alfa))/m)-(tr*g*sin(alfa))
];
------------------------------------------------------
Errors:
Error in naloga6>desne_strani (line 35)
y(4)
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode23 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in naloga6 (line 15)
[t,Y] = ode23(@desne_strani, [tstart tfinal],y0,[],g,m,k1,k2,alfa,tr);
Stephen Cobeldick on 13 May 2021
The ode23 documentation states that "y0 must be the same length as the vector output of odefun". In your code y0 has two elements, but your output has six elements. You need to fix this.
The error is caused by you defining y0 with two elements, which then defines the size of y provided to your function handle, but inside the function handle you try to access elements 3, 4, and 6 (which clearly do not exist in a two-element vector). You need to fix this too.
Avoid using undocumented and obsolete ways to pass parameter value to the objective function, much better is to follow the MATLAB documentation:

Walter Roberson on 13 May 2021
y(6)
Your code expects 6 (or more) boundary conditions are going to be passed in
y0 = [L*cos(alfa);L*sin(alfa)];
but your boundary conditions, y0, is a vector of length 2, not 6.
Nejc Jansa on 13 May 2021
Working now, thank you very much