Index exceeds the number of array elements

I don't understand why Matlab warns me with "Index exceeds the number of array elements. Index must not exceed 1" and stop the run at ode45's line. Please, help me to understand
function [integr] = costfunct(ks,cs,M,m)
% funzione costo per minimizzare gli spostamenti della massa sospesa
%[zt,M_pos,T] = response(Ks,Cs,M,m);
kt = 50000;
ti = 0;
tf = 10;
g = 9.80665;
T = linspace(0,5,1000); % tempo
zt = 100*sin(10*pi*T); % motion
xd = @(x,M,m,cs,ks,kt,zt,g) [x(2); 1/M*(cs*x(4)+ks*x(3)-cs*x(2)-ks*x(1))-g;x(4);1/m*(cs*x(2)+ks*x(1)-cs*x(4)-(ks+kt)*x(3)+kt*zt-(m+M)*g)];
%xd = diff_eq(M,m,ks,cs);
[~,M_pos] = ode45(xd,[ti tf],[0 0 0 0],optimset);
z0 = zeros(size(M_pos,2));
integr = immse(M_pos,z0);
end

Answers (1)

[~,M_pos] = ode45(xd,[ti tf],[0 0 0 0],optimset);
That line is going to take whatever xd is and attempt to pass two parameters into it: current time and current boundary conditions, in that order
xd = @(x,M,m,cs,ks,kt,zt,g) [x(2); 1/M*(cs*x(4)+ks*x(3)-cs*x(2)-ks*x(1))-g;x(4);1/m*(cs*x(2)+ks*x(1)-cs*x(4)-(ks+kt)*x(3)+kt*zt-(m+M)*g)];
The xd anonymous function is going to receive the scalar passed time into the first parameter, x, and the vector passed boundary conditions into the second parameter, M -- and m, cs, ks, kt, zt and g are going to be undefined inside the function.
The first thing the anonymous function does it to try to index x(2) but x is the received time which is a scalar, so you would get an index-out-of-range error.
What you should have defined is
xd = @(t, x) [x(2); 1/M*(cs*x(4)+ks*x(3)-cs*x(2)-ks*x(1))-g;x(4);1/m*(cs*x(2)+ks*x(1)-cs*x(4)-(ks+kt)*x(3)+kt*zt-(m+M)*g)];

3 Comments

Finally i don't have this kind of error, but another has appeared: "Error using vertcat. Dimensions of arrays being concatenated is not consistent". I don't know what is wrong, because only zt is a vector, while the other terms are constants.
Torsten
Torsten on 12 Jun 2023
Edited: Torsten on 12 Jun 2023
Check the sizes of the "constants".
We cannot tell because we don't know about ks,cs,M,m.
I solved the problem coding like this:
xd = @(t,x) [x(2); 1/M*(cs*x(4)+ks*x(3)-cs*x(2)-ks*x(1))-g;x(4);1/m*(cs*x(2)+ks*x(1)-cs*x(4)-(ks+kt)*x(3)+kt*100*sin(10*pi*t)-(m+M)*g)];
so I replaced zt with its own expression.
Thank everybody for the precious help!

Sign in to comment.

Tags

Asked:

on 11 Jun 2023

Edited:

on 12 Jun 2023

Community Treasure Hunt

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

Start Hunting!