How to use fminsearch or fmincon and return only positive values

17 views (last 30 days)
Hello everyone,
I am very new to MatLab and programming in general (<2 weeks of experience), so I apologize if my answer seems stupidly simple to everyone. I am trying to use solve a function using the minimizer and have it only return positive values. There are not matrices involved or anything.
This is my code:
if strcmp(channel,"trapezoidal")
T1 = m*2*yus+b;
A1=m*(yus^2)+b*yus;
Fr1 = ((Q^2*T1)/(g*(A1^3)))^(1/2);
Aybar1=(m/3)*(yus^3)+(b/2)*(yus^2);
M1=(Q^2)/(g*A1)+Aybar1;
fun=@(y2)abs(M1-(Q^2)/(g*(m*(y2^2)+b*y2))-((m*(y2^3)/3)+b*(y2^2)/2));
if Fr1<1
y2_guess=yus/100;
elseif Fr1>1
y2_guess=yus*100;
end
y_answer=fminsearch(fun,y2_guess);
fprintf('The conjugate depth (ft) in the channel is: %.2f \n', y_answer)
As you can see, it calculates M1 from previous values entered, then subtracts a bunch of stuff from it. With b=15, Q=2300, g=32.17, m=2, and yus= 10.22, I get a value for y_answer of 4, which is good. The way the phsyics of this situation work, if I then enter all the same values except for yus=4 now, I should get 10.22 back, but I get -11.25. I know for sure that 10.22 is one of the answers. I want it to somehow ignore negative values and "keep looking" if that makes sense.
For those curious, this is a momentum equation for a trapezoidal open channel carrying water. The two values 10.22 and 4 are called conjugate depths, i.e. they are two solutions to the same momentum equation. The negative value is not physically possible, because depth cannot be negative obviously.
Sorry if this has been asked. I did try googling it and I either did not understand the answer, or it wasn't relevant.

Accepted Answer

Walter Roberson
Walter Roberson on 5 Mar 2019
fminsearch is only for unbounded searches . John D'Errico created a File Exchange contribution to extend fminsearch to bounded regions.
fmincon can easily be used with bounds constraints . See the lb and ub parameter in the fmincon documentation .
Note that you will need to pass [] as the parameter for A, b, Aeq, beq positions . You cannot omit a positional parameter just because you are not using it.
  3 Comments
Walter Roberson
Walter Roberson on 5 Mar 2019
Yes.
I prefer to use variables for those positions to make it clearer what is happening:
A = []; b = [];
Aeq = []; beq = [];
lb = 0; ub = [];
nonlcon = [];
fmincon(fun, xo, A, b, Aeq, beq, lb, ub, nonlcon)
I do not know what you intend with your second 0 and then the -1 ?
Brian Fairchild
Brian Fairchild on 23 Apr 2019
Thank you very much! Sorry for the late reply. I have been meaning to come back to this post and tell you it worked out.

Sign in to comment.

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!