Index exceeds the number of array elements
Show older comments
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)
Walter Roberson
on 11 Jun 2023
[~,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)];
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!