How to avoid 'Index in position 1 is invalid.'

조회 수: 2 (최근 30일)
AelinAG
AelinAG 2018년 9월 11일
답변: Image Analyst 2018년 9월 11일
If I ask matlab to give me for example A(i - 1, j - 1) and A(i, j + 1) if matrix A and indices i, j are given, and one of them doesn't exist(because 'Index in position 1 is invalid'), how do I ignore the element that doesn't exist but print the other element(s)? For example, is there a function to test if those elements exist? Thanks!

답변 (1개)

Image Analyst
Image Analyst 2018년 9월 11일
Well you could let it throw an error. Or you could detect it in advance and throw a "friendlier" error
[rows, columns] = size(A);
row = i - 1; % Whatever....
col = j + 1;
if row < 1 || row > rows
warningMessage = sprintf('Error for i=%d, i-1 would give a row outside the range [1, %d], i, rows);
uiwait(errordlg(warningMessage));
end
if col< 1 || col > columns
warningMessage = sprintf('Error for j=%d, this would give a column outside the range [1, %d], j, columns);
uiwait(errordlg(warningMessage));
end
Or something similar. Or you could clip the values to the valid range.
row = max(1, i-1);
row = min(row, rows);
col = max(1, j-1);
col = min(col, columns);

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by