MATLAB: How to specify limits for lsqnonlin

lsqnonlinMATLAB

I would like to specify that variables in my lsqnonlin fit are real. The other vectors in my problem are complex so I cannot use a fully real solver.
My function has the following form. r and theta are real-valued coordinate matrices. Intensity is a complex valued matrix. p is the real-valued and positive vector (at least that is what I want to specify). Hej is the function to be minimized.
Hej= @(p)(p(1)*besselj(1,p(2)*r)+(p(4)*besselj(1,p(6)*r).*cos(theta+p(8))+p(9)*besselj(1,p(6)*r).*sin(theta+p(8)))*exp(1i*p(5))).*(r/a<=1) ...
+ (p(1)*besselj(1, p(2)*a)/besselk(1, p(3)*a)*besselk(1,p(3)*r)+...
(p(4)*besselj(1, p(6)*a)/besselk(1, p(7)*a).*cos(theta+p(8))+p(9)*besselj(1, p(6)*a)/besselk(1, p(7)*a).*sin(theta+p(8))).*exp(1i*p(5))).*(r/a>1)...
-Intensity;
opts = optimoptions(@lsqnonlin,'DiffMaxChange', 0.1,'FinDiffType', 'central', 'Display','off','MaxFunEvals',2E7,'TolFun',1E-18,'TolX',1E-24,'MaxIter',4E3);
x0 = st; % arbitrary initial guess
lb = 0.0*ones(size(st));
[p_estimated,resnorm,residuals,exitflag,output] = lsqnonlin(Hej,x0, lb,[], opts);
The initial guess is given as real-valued and positive vector.
So how do I specify that the only valid solution are positive and realvalued?

Best Answer

Implement the objective function as follows, splitting Hej into real and imaginary parts,
function out=objective(p,Intensity,r,theta)
Hej = (p(1)*besselj(1,p(2)*r)+(p(4)*besselj(1,p(6)*r).*cos(theta+p(8))+p(9)*besselj(1,p(6)*r).*sin(theta+p(8)))*exp(1i*p(5))).*(r/a<=1) + (p(1)*besselj(1, p(2)*a)/besselk(1, p(3)*a)*besselk(1,p(3)*r)+(p(4)*besselj(1, p(6)*a)/besselk(1, p(7)*a).*cos(theta+p(8))+p(9)*besselj(1, p(6)*a)/besselk(1, p(7)*a).*sin(theta+p(8))).*exp(1i*p(5))).*(r/a>1)-Intensity;
out=[real(Hej); imag(Hej)]; %Split into real and imaginary parts
end
and the minimization as
lsqnonlin(@(p)objective(p,Intensity,r,theta) , x0, lb,[], opts);