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

2 vues (au cours des 30 derniers jours)
AelinAG
AelinAG le 11 Sep 2018
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!

Réponses (1)

Image Analyst
Image Analyst le 11 Sep 2018
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);

Catégories

En savoir plus sur Debugging and Analysis dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by