MATLAB: How to format the nonlinear equations to find solutions

function nonlinear equations

I would like to write a function to solve two nonlinear equations in order to find K and a and use the solved K and a in other function later, that is, K=a*P(K); 1=a*Q(K). P(K)and Q(K) are two complicated expressions with respect to K. How to format this?

Best Answer

function ncf = N(x)
%ncf = 0.5*(1+erf(x/sqrt(2)));
xr = real(x);
xi = imag(x);
if abs(xi)>1e-10
error 'imag(x) too large in N(x)'
end
ncf = 0.5*(1+erf(xr/sqrt(2))) + i*xi.*exp(-0.5*xr.^2)/sqrt(2*pi);
end
function [K,alpha] = alphaCrit(S,r,sigma,T)
x0 = [1 2];
sol = fsolve(@(x)fun(x,S,sigma,T),x0)
K = sol(1);
alpha = sol(2);
end
function res = fun(x,S,sigma,T)
K = x(1);
alpha = x(2);
d2 = ( log(S) - log(K) + (r-0.5*sigma^2)*T ) / (sigma*sqrt(T));
res(1) = K - alpha * exp(-r*T)*N(-d2);
res(2) = 1 - alpha * exp(-r*T)/(sqrt(2*pi*sigma^2*T)*K)*exp(-0.5*d2^2);
end