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 件のコメント
madhan ravi
madhan ravi 2018 年 9 月 11 日
example?

サインインしてコメントする。

回答 (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 Center および File ExchangeDebugging and Analysis についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by