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

2 visualizaciones (últimos 30 días)
AelinAG
AelinAG el 11 de Sept. de 2018
Respondida: Image Analyst el 11 de Sept. de 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!

Respuestas (1)

Image Analyst
Image Analyst el 11 de Sept. de 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);

Categorías

Más información sobre Debugging and Analysis en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by