MATLAB: Initial guess Error using fsolve

error using fsolve

This is my code
clear all
tic
% fun= @(x)qfunc(2-0.5*x)*exp(-x^2);
% %
P0=0.5;
P1=1-P0;
P=P0/P1;
rho=0.3; %covariance
s1=0.5; %mean of sensor 1
s2=1;%mean of sensor 2
Sm=max(s1,s2);
t1=-20:0.01:20 ; %threhsold for sensor 1
stop=0;
stop_1=0;
for i=1:length(t1)
fun= @(x2) exp(-s2.^2./2).*exp(x2.*s2).*qfunc((t1(i)-s1-rho.*x2+rho.*s2)./sqrt(1-rho.^2))-P.*qfunc((t1(i)-rho.*x2)./sqrt(1-rho.^2))
myfun= @(y) exp(-s2^2./2).*exp(y*s2)*(1-qfunc((t1(i)-s1-rho*y+rho*s2)./sqrt(1-rho^2)))./(1-qfunc((t1(i)-rho.*y)./sqrt(1-rho^2)))-P;
y0=rand;
tw0=fsolve(myfun,y0);
end
I get this error msg ''Objective function is returning undefined values at initial point. fsolve cannot
continue.''
I think the function handle becomes of 0/0 form for initial guess because of qfunc of what I have underlined. How do I put a condtion to use the approximate of qfunc whenever the fsolve counters 0/0 form?

Best Answer

NZ = @(a,b) a ./ (b + (a==0 & b == 0));
myfun=@(y) exp(-s2^2./2).*exp(y*s2).*NZ(1-qfunc((t1(i)-s1-rho*y+rho*s2)./sqrt(1-rho^2)),1-qfunc((t1(i)-rho.*y)./sqrt(1-rho^2)))-P;
This detects the case where numerator and denominator are both 0, and substitutes 1 for the denominator in that case, giving a 0/1 result. Perhaps you might prefer
NZ = @(a,b) (a + (a==0 & b == 0)) ./ (b + (a==0 & b == 0));