MATLAB: Avoiding negative values in fminsearch

optimization

Hello, I am doing optimisation of a guassian function to calculate the midpoint and spread when the function below goes to zero. But when using fminsearch i get negative values.What i am supposed to get is 24 and 4 respectively please help!!
AA=1.580740308;
BB=0.854284221;
format long g
invalues=[1,10];
fun1=@(x)((AA-sum(A.*real(exp(-((E-x(1)).^2/x(2).^2)))))^2+...
(BB-sum(B.*real(exp(-((E-x(1)).^2/x(2).^2)))))^2);
[x,fval]=fminsearch(fun1,invalues)

Best Answer

All of your terms involving x are squared, so there is no way to tell a negative value of the term from a positive value of the term. Negative x are valid solutions.
It is not possible to constrain fminsearch to prevent it from using negative x. The closest you could get would be to add a penalty, such as
fun1=@(x)((AA-sum(A.*real(exp(-((E-x(1)).^2/x(2).^2)))))^2 + ...
(BB-sum(B.*real(exp(-((E-x(1)).^2/x(2).^2)))))^2) + ...
10^100 * any(x < 0);