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

Kaleesh Bala

Kaleesh Bala (view profile)

さんによって質問されました 2018 年 7 月 3 日

Kaleesh Bala (view profile)

さんによって コメントされました 2018 年 7 月 3 日
Guillaume

Guillaume (view profile)

さんの 回答が採用されました
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 件のコメント

サインイン to comment.

R2018a

1 件の回答

Guillaume (view profile)

on 3 Jul 2018

Isn't the problem obvious?
Your Is is a 4x1 column vector. It only has one column, therefore asking for the 1st element of column 2, 3 and 4 as you do in your D calculation is invalid. All that stems from the fact that you made an assumption that the vector was a row vector and used 2d indexing to access its elements. You would have avoided this problem if you'd used linear indexing since then it doesn't matter if the vector is a row or column:
D = sqrt(Is(2) - Is(1))^2 + (Is(4)-Is(3))^2;
and it's easier to read as well.
Note for better accuracy:
D = hypot(Is(2)-Is(1), Is(4)-Is(3));

Kaleesh Bala

Kaleesh Bala (view profile)

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

サインイン to comment.