Test for within cell array boundaries

2 views (last 30 days)
Is there a test for whether or not a cell is within a cell array's boundaries?
For example, myarray = cell(8);
inbounds(myarray{8,8})
1
inbounds(myarray{9,9})
0
Is there an actual function equivalent to my inbounds?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 27 May 2017
Edited: Andrei Bobrov on 27 May 2017
inbounds = @(myarray,indexes)all(size(myarray) >= indexes(:)');
use:
>> inbounds = @(myarray,indexes)all(size(myarray) >= indexes(:)');
myarray = randi(125,10,8);
out = inbounds(myarray,[2 6])
out =
logical
1
>>

More Answers (1)

Jan
Jan on 27 May 2017
Edited: Jan on 27 May 2017
myarray = cell(8);
search = [9, 9];
if all(search <= size(myarray))
... existing
You can create such a function easily:
function ok = inbounds(X, Index)
if numel(Index) == ndims(X)
ok = all(Index > 0) && all(Index == round(Index)) && all(Index <= size(X));
elseif numel(Index) == 1
ok = (Index <= numel(X));
else
ok = false;
end
You could or should expand this to consider the convention that trailing singelton dimensins are ignored in Matlab:
X = rand(2,3);
X(2,2,1,1,1,1,1) % Ok!
An explicite test inside the code might be smarter than such a general method.

Community Treasure Hunt

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

Start Hunting!