Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
Jason S Avatar asked Oct 04 '10 13:10

Jason S


2 Answers

Aha, I got it:

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

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

like image 74
Jason S Avatar answered Sep 23 '22 04:09

Jason S


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
like image 24
Steve Eddins Avatar answered Sep 25 '22 04:09

Steve Eddins