Substituting a number for NaN in anonymous function

8 次查看(过去 30 天)
I'm trying unsuccessfully to substitute a number for NaN in anonymous function. Here it's an example of the problem. Bear with it's silliness please:
clc;
clear all;
f=@(x) x*1/x;
g=@(x) (~isnan(f(x))).*f(x) + (isnan(f(x))).*1;
I'd expect that g(0)=1, but it's still NaN. What is wrong in the way that I defined g?
  2 个评论
John
John 2015-1-13
Your replies made me understand why it didn't work. However, in attempting to overcome this problem, I still don't grasp why the following happens:
clc;
clear all;
f1=@(x) x.*(1./x);
g(0,f1) %ok, got the desired result
y=linspace(0,1,10);
g(y(1),f1) %good
g(y,f1) %didn't work: first element is NaN
function out=g(x,f1)
fval=f1(x);
if isnan(fval)==1;
out = 1;
else
out=fval;
end
end
From this, I can see that I can construct the function "element-wise". But how to do it for the whole vector?
Guillaume
Guillaume 2015-1-13
It's getting a bit messy. You should have accepted the answer that helped you the most and started a new question. Don't pile questions on top of questions, because now there's no appropriate place to answer your new question.
Anyway, the reason why it does not work in the second case is that isnan(fval) == 1 (which is just the same as isnan(fval)) is a logical vector equal to
1 0 0 0 0 0 0 0 0 0 0
If you pass a vector to if it will only evaluate to true if and only if all elements are not zeros. Therefore your expression is false.
To fix this:
if any(isnan(fval))
out = 1;
else
out = fval;
end
Or if you just want to replace the Nans by 1:
fval(isnan(fval)) = 1; %no need for if

请先登录,再进行评论。

采纳的回答

Alfonso Nieto-Castanon
编辑:Alfonso Nieto-Castanon 2015-1-13
There may be "cleaner" ways to do this but one possibility would be:
g = @(x) [f(x) 1]*sparse(1+isnan(f(x)),1,1,2,1);
EDIT: and as others have pointed out the problem with your original g function is that, when f(x) is NaN, you get 0*NaN + 1*1 which still evaluates to NaN...

更多回答(2 个)

John Petersen
John Petersen 2015-1-13
You have .*f(x) in g(x), which is still giving you a NaN

Star Strider
Star Strider 2015-1-13
If you want to define L’Hospital’s rule, you have to define it specifically. In the IEEE standard that MATLAB implements, 0/0 is NaN.
See if this works in your application:
n = @(x) 2.*x; % Numerator Function
d = @(x) x; % Denominator Function
Lh = @(n,d,x) (n(x+1E-12)-n(x)) ./ (d((x+1E-12)-d(x))); % L’Hospital’s RUle
Lh0 = Lh(n,d,0) % Evaluating AT 0
Lh2 = Lh(n,d,2) % Evalutaing At 2

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by