How to avoid 'Index in position 1 is invalid.'
1 回表示 (過去 30 日間)
古いコメントを表示
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
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);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!