"Index exceeds array dimensions. Index value 2 exceeds valid range [1-1] for array" --How to solve this?

조회 수: 82(최근 30일)
Whenever I am trying to update a 2-dimensional array in a loop matlab throws this error!
%% initialized in workspace
%% update via a function
for i=1:10 % implemented via simulink counter and increment block
func op= fcn(i)

채택된 답변

Walter Roberson
Walter Roberson 2020년 10월 21일
In Simulink,
defines s.t as being a scalar value that is not permitted to increase in size.
In Simulink, you need to initialize variables to the maximum size they could use. You can reduce the size of the variable later if you need to, but you cannot increase it in size. (See, though, coder.varsize() )
Your code runs to s.t(10+1) so your s.t is length 11. Initialize it as
s.t = zeros(11,1);
  댓글 수: 1
Sunandan Adhikary
Sunandan Adhikary 2020년 10월 22일
Great. This helped. Unlike normally as we do in matlab scripts, while updating the variable in a function, we must let the function know its size as well. So prior initialization of the whole matrix is needed.

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

추가 답변(1개)

Prudhvi Peddagoni
Prudhvi Peddagoni 2020년 10월 21일
The error you mentioned occurs when you try to access an array element which is out of it's length.
If you are trying to update s.t array such that s.t(i+1)=i*0.1
for i=1:10
if not, can you post more information about what you are trying to do
Hope this helps.
  댓글 수: 1
Sunandan Adhikary
Sunandan Adhikary 2020년 10월 21일
편집: Sunandan Adhikary 2020년 10월 21일
I have done exactly what you mentioned. Running this will return no error. But since this operation happens in a function block in simulink model, that takes value of i as input (I increase i in every sampling period and input to the function block) and the intializations are in different script, I get such error! I have mentioned in the comment how did I implement it. Can uou help?

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


Find more on Simulink Functions 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!

Translated by