Jason S
Jason S

Reputation: 189686

matlab: quick function that can produce NaN if x > 1

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

Any suggestions?

Upvotes: 7

Views: 587

Answers (4)

Steve Eddins
Steve Eddins

Reputation: 1311

Here's a modification of Jason's solution that works for arrays. Note that recent versions of MATLAB do not throw divide-by-zero 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 coworker pointed out to me that Jason's original answer works just fine for arrays.

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

f = 

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

>> f(0:.3:2)

ans =

     0     0     0     0   NaN   NaN   NaN

Upvotes: 5

gnovice
gnovice

Reputation: 125864

Here's a solution that won't risk throwing any divide-by-zero warnings, since it doesn't involve any division (just the functions ONES and NAN):

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


EDIT: The above solution is made for scalar inputs. If a vectorized solution is needed (which isn't 100% clear from the question) then you could modify f like so:

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

Or apply ARRAYFUN when calling the first version of the function f:

y = arrayfun(f,x);

Upvotes: 2

Amro
Amro

Reputation: 124563

Here's a less obvious solution (vectorized nonetheless):

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

Basically its equivalent to:

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

The +0 at the end is to always force an output, even if f called with no output arguments (returned in ans). Example:

>> f(-2:2)
ans =
     0     0     0   NaN   NaN

Upvotes: 2

Jason S
Jason S

Reputation: 189686

Aha, I got it:

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

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

Upvotes: 5

Related Questions