Index exceeds the number of array elements (11).

This is my script.
L_S = [37.752: L_delta_S : 83.483]';
W_S = [12.995 : W_delta_S : 23.6205]';
for S1 = 1:length(L_Possible_States)
for S2 = 1:length(W_Possible_States)
% First part
m = S2 + (11*S1 - 11);
L_Possible_States(m,1) = L_S(S1);
% Second part
W_Possible_States(m,1) = W_S(S2);
W_H(m,1) = -0.7469179561*W_Possible_States(m,1) + 0.0021132084*W_Possible_States(m,1)^2 + 15.62636759*W_Possible_States(m,1)^0.5 + 573.017896;
Wdischarge(m,1) = 18775;
Wpower(m,1) = WP(1,1)* W_H(m,1) + WP(1,2);
end
end
Index exceeds the number of array elements (11).
Error in Mywork (line 203)
W_Possible_States(m,1) = W_S(S2);
I have searched similar problems but still cannot handle this. Is anyone can help me? Thanks!

 Accepted Answer

Jan
Jan on 13 Mar 2021
Edited: Jan on 13 Mar 2021
The message tells you, that you try to access W_S(12), but W_S has 11 elements only. This means that
W_S = [12.995 : W_delta_S : 23.6205]'
has less elements than length(W_Possible_States). The readers cannot guess, how you can handle this.
Notes:
  • length is fragile, if the input is an array with multiple dimensions. It helps to avoid bugs if you use size(., dim) instead and specify the wanted dimension explicitly
  • [12.995 : W_delta_S : 23.6205]' Remember that [ ] is the operator for concatenation in Matlab. a:b:c is a vector already, so it is a waste of time to concatenate it with nothing. So this is a tiny improvement: (12.995:W_delta_S:23.6205).'
  • sqrt(x) is 40% faster than x^0.5 . Even if the speed is not important here, it is a good programming practize to avoid loosing time.

More Answers (0)

Asked:

on 13 Mar 2021

Commented:

on 13 Mar 2021

Community Treasure Hunt

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

Start Hunting!