Best way to solve my equation.

1 view (last 30 days)
Francois
Francois on 12 Mar 2015
Answered: Francois on 23 Mar 2015
Hello, I am trying to solve an equation and to optimize the solver. However, since Matlab offers several ways to do so, I am a little bit lost regarding the best way for my case.
I have a somehow very long formula with only one variable that I will call z. Thus, the formula is f(z) and I am seaching for the z such as abs(f(z))=2.
As far as I know, I have three ways to do so:
f = myfunction;
f = abs(f)-2;
sol = fzero(f,z);
f = myfunction;
f = abs(abs(f)-2);
sol = fminsearch(f,z);
syms z;
f = myfunction;
sol = double(solve(f==2))
I guess using syms is not the fastest so I should probably be one of the two others but which one? Plus, there might also be other solvers that I don't know about. Futhermore, I am struggling with the options and on how to optimize the solution finding. For exemple, I know the minumal and maximal values that z could potentially take and I think that fidding the solver with that might help reducing the time.
Last thing, for one of my case, I ploted f(z) to see how it looks like and if the solutions I was given were right. The case I tested has four solutions. However, I get only two solutions with fminsearch and sym and those two are correct ones but the two ways of solving don't give me the same correct ones. That is also for that that I am posting here because I probably don't use the solver correctly.

Answers (2)

Alan Weiss
Alan Weiss on 12 Mar 2015
I would use fzero or fminbnd, not fminsearch. For both fminbnd and fzero, you would do well to give a finite initial interval (you have to for fminbnd). If you do so for fzero then the function needs to have opposite signs at the endpoints. In this case, either algorithm will converge quickly. Probably fzero will be faster, but I am not 100% certain about that.
Alan Weiss
MATLAB mathematical toolbox documentation

Francois
Francois on 23 Mar 2015
Thanks for your answer. I decided to use fminbnd over fzero because the function doesn't necessary have opposite signs at the end points. Thus, I do:
x1 = fminbnd(fun,x01,x02);
With x1 < x2.
I was thinking that it would go from x1 to x2 and find the root the closest from x01. Thus, I thought that I would do:
x2 = fminbnd(fun,x1+dx,x02);
So it would find the second root and so on. The example I choose to try has four roots x1 < x2 < x3 < x4. However, it gave me the root the closest to x02. Ok, no problem, I will just do the opposite. But then, when I did:
x4 = fminbnd(fun,x01,x02);
x3 = fminbnd(fun,x01,x4-dx);
while making sure x4-dx > x3. Then, instead of giving me the root just before x4, it gave me the second one x2. I am sure that there is a way around that but I can't find it.

Categories

Find more on Optimization in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!