check if index is out of array in matlab

You can use the numel function to obtain the number of elements in the array. Then, use an if statement to check if the index is within the bounds of the array. Here is an example:

main.m
arr = [1, 2, 3, 4, 5];
idx = 6;

if idx > numel(arr) || idx < 1
    disp('Index is out of bounds')
else
    disp('Index is within bounds')
end
143 chars
9 lines

In this example, the index 6 is out of bounds, so the output would be 'Index is out of bounds'. If the index was 3, the output would be 'Index is within bounds'.

related categories

gistlibby LogSnag