Checking Matlab indices exists, returning boolean value
61 views (last 30 days)
Show older comments
Hi, is there any function to check, if a Matrix index exists or not. Like if(K(i,j))
should be zero if there is no value or the index does not exists, this works in C++, C# etc.. Is there any function in Matlab. Like I am accessing every pixel, and its 8 neighbourhood,
please suggest.
Regards
0 Comments
Answers (2)
Walter Roberson
on 15 Apr 2013
I'm pretty sure you cannot do that in C++.
It is not possible for there to be "no value" for a numeric matrix entry in MATLAB. It is possible for the entry to be NaN, though, provided that it is a floating-point datatype.
K(i,j) exists in MATLAB if "i" and "j" are positive, are integral, and if i <= size(K,1) and if j <= (numel(K) / size(K,1)). That last bit is probably unfamiliar to you: if K is a matrix with more than 2 dimensions then you can index it with two indices anyhow.
If you are sure that K is two-dimensional (which is often not the case for images), then the check becomes that i <= size(K,1) and j <= size(K,2)
There is no documented routine to do this kind of check.
4 Comments
Zangdaarr
on 24 Feb 2016
function oValue = isIndexValid(iTable,iIndex)
try
if(isa(iTable,'cell'))
iTable{iIndex}; %#ok<*VUNUS>
else
iTable(iIndex);
end
oValue = true;
catch %#ok<CTCH>
oValue = false;
end
end
Just replace the inner code with an eval so you can pass your index as a string, and this function will work with any dimension table.
There is no native function in C/C++ to check this but you can do the same. However, it is generally not recommended to start try/catching null pointers or unknown allocated memory zone in C++, and exception are not really good for performances. You'd rather simply use containers that can return their size.
This is also what you should do in Matlab, however, since the point above is less an issue with Matlab, this function is actually cool to make code more readable.
1 Comment
Guillaume
on 24 Feb 2016
Not sure why this is being revived two years later?
While exception handling should be part of any decent code, I don't agree that in this case it makes "code more readable". This:
oValue = iIndex < numel(iTable)
is in my opinion a lot clearer as to its purpose.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!