A problem with function handle

조회 수: 1 (최근 30일)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022년 11월 6일
댓글: Mohammad Shojaei Arani 2022년 11월 6일
Hello,
I have a simple problem but I do not understand why function handle behaves like this!!! I explain by a simple example in bellow:
>> x1=linspace(-pi,pi,20);y1=sin(x1);f=@(x)interp1(x1,y1,x);f(5)
ans =
NaN
which makes sense. But, when I type
>> x1=linspace(-pi,pi,20);y1=sin(x1);f=@(x)interp1(x1,y1,x).*(x>=-pi & x<=pi)+0.*(x<-pi | x>pi);f(5)
ans =
NaN
and this does not make sense to me.
Any idea?
Thanks in advance,
Babak

채택된 답변

John D'Errico
John D'Errico 2022년 11월 6일
편집: John D'Errico 2022년 11월 6일
NaNs are like wire coathangars, they multiply. Or perhaps evil zombies is a better description. They slime everything they touch, turning everything into new NaNs, propagating NaNs almost everywhere. Evil indeed. ;-)
For example, NaN plus ANYTHING = NaN.
NaN + 2
ans = NaN
NaN times ANYTHING = NaN. Even zero.
NaN*0
ans = NaN
So what did you do? You were hoping the trick of putting a test inline, that a multiply by zero would kill off the NaNs? Yeah, right. The zombies still survived.
Instead, you do have an option. Read the help for interp1!
x1=linspace(-pi,pi,20);
y1=sin(x1);
extrapval = 42;
f=@(x)interp1(x1,y1,x,[],extrapval);
f(5)
ans = 42
I cannot understand why interp1 uses NaN as the default for extrapolation, as 42 has been proven to be the answer to all questions. But if you really want zero to be returned, you can tell interp1 to do that too.
  댓글 수: 2
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022년 11월 6일
Oh! I got the problem. Am trying to dix it. Thanks John. Indeed, they are like zombies. It is a headache
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022년 11월 6일
Thanks John!
I came up by an idea to solve it. But, your way of solving the problem is much more elegant than mine!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by