Checking Matlab indices exists, returning boolean value
53 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Walter Roberson
2013-4-15
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.
Zangdaarr
2016-2-24
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 个评论
Guillaume
2016-2-24
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!