MATLAB Answers

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

4.265 views (last 30 days)
Kaleesh Bala
Kaleesh Bala on 3 Jul 2018
Answered: sachin bharadwaj on 5 Nov 2020 at 6:52
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

  0 Comments

Sign in to comment.

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.

  1 Comment

Kaleesh Bala
Kaleesh Bala on 3 Jul 2018
Yup! sorry, it was assumed to be a row vector. Now it works fine!
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);
fprintf('the value of Is %d',Is)
%Eucleidan distance
D = hypot(Is(3)-Is(1), Is(4)-Is(2));
fprintf ('the distance value obtained Dis %d',D)
end

Sign in to comment.

More Answers (1)

sachin bharadwaj
sachin bharadwaj on 5 Nov 2020 at 6:52
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?

  0 Comments

Sign in to comment.

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by