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

답변 (1개)

Walter Roberson
Walter Roberson 2023년 6월 11일

0 개 추천

[~,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

Alessio
Alessio 2023년 6월 12일
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 2023년 6월 12일
편집: Torsten 2023년 6월 12일
Check the sizes of the "constants".
We cannot tell because we don't know about ks,cs,M,m.
Alessio
Alessio 2023년 6월 12일
편집: Alessio 2023년 6월 12일
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!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2023년 6월 11일

편집:

2023년 6월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by