Reputation: 571
I want to write a function in Matlab for
This is what I wrote.
function f=hamacher(x,y)
for i=1:5
if x==0.00 & y==0.00
f=0;
else
f=(x.*y)./(x+y-(x.*y));
end
end
end
If I let
>> p=[0 0.5 1 0 0.75];
>> q=[0 0.2 0 0 0.8];
>> hamacher(p,q)
ans =
NaN 0.1667 0 NaN 0.6316
This results NaN
and not 0
because of 0/0
. I want to handle this issue by
if x==0.00 & y==0.00
f=0;
Why doesn't this if
statement handle this?
Can someone please tell me how I can correct this.
Upvotes: 1
Views: 136
Reputation: 112769
Since your function is vectorized, use logical indexing to distinguish the two cases element-wise:
ind = x==0 & y==0;
f(ind) = 0;
f(~ind) = x(~ind).*y(~ind)./(x(~ind)+y(~ind)-(x(~ind).*y(~ind)));
Upvotes: 3
Reputation: 18197
function f=hamacher(x,y)
f = zeros(numel(x),1);
for ii=1:numel(x)
if x(ii)==0 && y(ii)==0
f(ii,1)=0;
else
f(ii,1)=(x(ii)*y(ii))/(x(ii)+y(ii)-(x(ii)*y(ii)));
end
end
end
>> p=[0 0.5 1 0 0.75];
>> q=[0 0.2 0 0 0.8];
>> hamacher(p,q)
ans =
0
0.1667
0
0
0.6316
I'm quite sure this is what you wanted. I just made sure everything works element wise and not vectorised.
Upvotes: 1