Matlab: a fast function that can produce NaN if x> 1

I am looking for a single-line function f = @(x) {something} that produces NaN if x> = 1, and either 0 or 1 if x <1.

Any suggestions?

+7
function matlab nan
source share
4 answers

Yeah, I get it:

 f = @(x) 0./(x<1) 

gives 0 for x <1 and NaN for x> = 1.

+5
source share

Here's a modification of the Jason solution that works for arrays. Note that recent versions of MATLAB do not generate zero-delimited warnings.

 >> f = @(x) zeros(size(x)) ./ (x < 1) f = @(x)zeros(size(x))./(x<1) >> f(0:.3:2) ans = 0 0 0 0 NaN NaN NaN 

Update : A colleague told me that Jason's original answer is suitable for arrays.

 >> f = @(x) 0./(x<1) f = @(x)0./(x<1) >> f(0:.3:2) ans = 0 0 0 0 NaN NaN NaN 
+5
source share

Here is a solution that will not risk throwing any warnings about division by zero, since it is not connected with any division (just the ONES and NAN functions):

 f = @(x) [ones(x < 1) nan(x >= 1)]; 


EDIT: The above solution is made for scalar inputs. If a vectorized solution is required (which is not 100% clear from the question), you can change f as follows:

 f = @(x) arrayfun(@(y) [ones(y < 1) nan(y >= 1)],x); 

Or use ARRAYFUN when calling the first version of f :

 y = arrayfun(f,x); 
+2
source share

Here's a less obvious solution (however, vectorized):

 f = @(x) subsasgn(zeros(size(x)), struct('type','()','subs',{{x>=1}}), nan) + 0 

Basically its equivalent:

 function v = f(x) v = zeros(size(x)); v( x>=1 ) = nan; 

+0 at the end - always force output, even if f is called without output arguments (returns to ans ). Example:

 >> f(-2:2) ans = 0 0 0 NaN NaN 
+2
source share

All Articles