MATLAB Answers

Index in position 2 exceeds array bounds (must not exceed 1) ??

4,152 views (last 30 days)
Kaleesh Bala
Kaleesh Bala on 3 Jul 2018
Commented: Walter Roberson on 5 May 2021 at 9:51
Why does the following function produce the error "Index in position 2 exceeds array bounds (must not exceed 1)"?
function test2
close all
prompt ={'Enter the x1 value: ','Enter the y1 value: ','Enter the x2 value: ','Enter the y2 value: '};
Is = inputdlg(prompt);
Is = str2double(Is);
%Eucleidan distance
D = sqrt((Is(1,2)-Is(1,1))^2 + (Is(1,4)-Is(1,3))^2);
fprintf ('the distance value obtained is %d',D)
end

Accepted Answer

Guillaume
Guillaume on 3 Jul 2018
Edited: MathWorks Support Team on 27 Feb 2020
The error occurs because the vector “Is” is a 4-by-1 column vector (not a 1-by-4 row vector) so that the valid element positions are (1,1), (2,1), (3,1), and (4,1). If you try to access any index value beyond 1 in the 2nd position, you will encounter the error.
  3 Comments
Walter Roberson
Walter Roberson on 5 May 2021 at 9:47
When you use xlsread(), the first output is trimmed down to remove all leading and trailing rows and columns that are all NaN after conversion to numbers. Typically that happens for header rows and for leading or trailing text columns. You first column probably has text in it, so it became all NaN when converted to numbers, and then got discarded. That would have thrown off your indexing.
We recommend that you switch to readtable().

Sign in to comment.

More Answers (1)

sachin bharadwaj
sachin bharadwaj on 5 Nov 2020
Index in position 2 exceeds array bounds (must not exceed 1).
Error in fatlabexam (line 17)
g=PP(:,1)*h(1)+PP(:,2)*h(2);
why is it showing error?

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!