Reputation: 35331
I find myself writing stuff like this a lot:
if isnumeric(X) & ~isnan(X)
% etc etc
end
Before I clutter the namespace with my own test
function out = isanumber(X)
out = isnumeric(X) & ~isnan(X);
end
does MATLAB already have an equivalent test?
Upvotes: 1
Views: 1319
Reputation: 283793
More than likely you want isfinite(X)
.
Admittedly it isn't exactly equivalent to isnumeric(X) & ~isnan(X)
, it's equivalent to isnumeric(X) & ~isnan(X) & ~isinf(X)
, but I'm guessing you don't want the other special cases (plus and minus infinity) either.
Upvotes: 2
Reputation: 38042
No, there isn't.
NaN
is of a numeric class (double
by default, conforming to IEEE754), which makes isnumeric
evaluate to true
when passed the NaN
. I'll immediately admit that the seemingly trivial
isnumeric ( not a number )
actually gives true is somewhat counter-intuitive, but it makes perfect sense when you're reading large amounts of data from a file for instance, and some elements of the matrices read thusly are NaN
(missing, misconverted or similar) -- in such cases, it would be pretty darn annoying if isnumeric(NaN)
would then say false
.
So as usual, it all depends on how you look at it. The MathWorks decided (quite possibly after a lot of research) that the cases in which it makes sense to return true
are far more numerous than the opposite. So, you'll have to always manually test both cases I'm afraid.
By the way, you wouldn't be cluttering so much if you just make it a sub- or nested function:
% All in the same file:
function varargout = main(varargin)
% Delegate checking, parsing, etc. the input arguments
% to a subfunction
[varargin{1:nargin}] = parseInputArguments(varargin{:});
% ...So you can just go on and do all your main stuff here
% without all the usual clutter of parsing the arguments
end
% Main's argument parser
function varargout = parseInputArguments(varargin)
% ...parse all sorts of stuff here
% the readable test:
if isanumber(varargin{2})
varargout{2} = rand(5); end
% ...parse more stuff here
% nested helper function to aid readibility without
% polluting the main function namespace too much
function yn = isanumber(x)
yn = isnumeric(x) & ~isnan(x);
end
end
Upvotes: 3