# Solve nonlinear equations with condition

3 views (last 30 days)
MENGZE WU on 22 Apr 2022
Commented: Walter Roberson on 23 Apr 2022
syms a1 a2
eqns = [1-2*cos(5*a1)+2*cos(5*a2) == 0, 1-2*cos(a1)+2*cos(a2) == pi/5];
vpasolve(eqns, [a1 a2], [0 pi/2])
Hi,
I would like to solve nonlinear equation like this but with a1<a2 and both of them are in the range of [0 pi/2], how can I do that? Also, if I solve this way, there is no solution.

Walter Roberson on 23 Apr 2022
syms a1 a2
eqns = [1-2*cos(5*a1)+2*cos(5*a2) == 0, 1-2*cos(a1)+2*cos(a2) == pi/5];
sol = vpasolve(eqns, [a1 a2], ones(2,1).*[0 pi/2])
sol = struct with fields:
a1: 0.38678049836383383777777870083222 a2: 0.73729835675575072765981215039016

Torsten on 22 Apr 2022
Edited: Torsten on 22 Apr 2022
Use "fmincon" with the objective
(1-2*cos(5*a(1))+2*cos(5*a(2)))^2 + (1-2*cos(a(1))+2*cos(a(2))-pi/5)^2
with the linear constraint
a(1) - a(2) <= 0
and the bound constraints
0 <= a(1),a(2) <= pi/2
fun = @(a)(1-2*cos(5*a(1))+2*cos(5*a(2)))^2 + (1-2*cos(a(1))+2*cos(a(2))-pi/5)^2;
A = [1 -1];
b = [0];
lb = [0, 0]
ub = [pi/2, pi/2];
a0 = [pi/8, pi/4];
a = fmincon(fun,a0,A,b,[],[],lb,ub)
fun(a)
Walter Roberson on 23 Apr 2022
You have two equations, A1==B1 and A2==B2 . Rewrite to A1-B1==0 and A2-B2==0
But suppose you do not have a root-finding function handy that can handle two equations simultaneously. Then instead of a root finding function, you can substitute a minimizer. Square both sides of each equation, (A1-B1).^2 == 0^2 and (A2-B2).^2 == 0^2 . Drop the right-hand sides, to get (A1-B1).^2 and (A2-B2).^2 and think about minimizing those squares: if A1==B1 then A1-B1 would be 0, so the closer (A1-B1).^2 is to 0, the better the match you get. With real-valued quantities, (A1-B1)^2 can never be negative, only 0 or positive, and 0 is ideal, so minimizing (A1-B1).^2 would give you "as close to equality as is feasible". And to handle both equations simultaneously, add the squares, (A1-B1).^2 + (A2-B2).^2 : if there were exact matches the subtractions would each give 0 and the squares would be 0 and the sums would be 0. But you might have the case where improving (A1-B1).^2 gives you a worse (A2-B2).^2 and vice versus, in which case minimizing the sum of squares drives the solution to the point where the error from one of them equals the error from the other one, not favouring either side in that case.

R2021a

### Community Treasure Hunt

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

Start Hunting!