Equations and systems solver
Support for character vector or string inputs has been removed. Instead, use syms
to declare variables and replace inputs such as solve('2*x ==
with
1','x')solve(2*x == 1,x)
.
Syntax
Description
example
S
= solve(eqn
,var
)
solves the equation eqn
for the variable var
. If
you do not specify var
, the symvar
function determines the variable to solve for. For example,
solve(x + 1 == 2, x)
solves the equation x + 1 = 2 for x.
example
S
= solve(eqn
,var
,Name,Value
)
uses additional options specified by one or more Name,Value
pair
arguments.
example
Y
= solve(eqns
,vars
)
solves the system of equations eqns
for the variables
vars
and returns a structure that contains the solutions. If you do
not specify vars
, solve
uses symvar
to find the variables to solve for. In this case, the number of
variables that symvar
finds is equal to the number of equations
eqns
.
example
Y
= solve(eqns
,vars
,Name,Value
)
uses additional options specified by one or more Name,Value
pair
arguments.
example
[
y1,...,yN
] = solve(eqns
,vars
)
solves the system of equations eqns
for the variables
vars
. The solutions are assigned to the variables
y1,...,yN
. If you do not specify the variables,
solve
uses symvar
to find the variables to
solve for. In this case, the number of variables that symvar
finds is
equal to the number of output arguments N
.
[
y1,...,yN
] = solve(eqns
,vars
,Name,Value
)
uses additional options specified by one or more Name,Value
pair
arguments.
example
[
y1,...,yN
,parameters
,conditions
]
= solve(eqns
,vars
,'ReturnConditions
',true)
returns the additional arguments parameters
and
conditions
that specify the parameters in the solution and the
conditions on the solution.
Examples
collapse all
Solve Quadratic Equation
Solve the quadratic equation without specifying a variable to solve for. solve
chooses x
to return the solution.
syms a b c x eqn = a*x^2 + b*x + c == 0
S =(-b+b2-4 a c2 a-b-b2-4 a c2 a)
Specify the variable to solve for and solve the quadratic equation for a
.
Solve Polynomial and Return Real Solutions
Solve a fifth-degree polynomial. It has five solutions.
syms x
eqn = x^5 == 3125;
S = solve(eqn,x)
S =(5-σ1-54-5 2 5-5 i4-σ1-54+5 2 5-5 i4σ1-54-5 2 5+5 i4σ1-54+5 2 5+5 i4)where σ1=5 54
Return only real solutions by setting 'Real'
option to true
. The only real solutions of this equation is 5
.
S = solve(eqn,x,'Real',true)
Numerically Solve Equations
When solve
cannot symbolically solve an equation, it tries to find a numeric solution using vpasolve
. The vpasolve
function returns the first solution found.
Try solving the following equation. solve
returns a numeric solution because it cannot find a symbolic solution.
syms x
eqn = sin(x) == x^2 - 1;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(fullfile(docroot, 'symbolic/vpasolve.html'))">vpasolve</a>.
S = -0.63673265080528201088799090383828
Plot the left and the right sides of the equation. Observe that the equation also has a positive solution.
fplot([lhs(eqn) rhs(eqn)], [-2 2])
Find the other solution by directly calling the numeric solver vpasolve
and specifying the interval.
V = vpasolve(eqn,x,[0 2])
V = 1.4096240040025962492355939705895
Solve Multivariate Equations and Assign Outputs to Structure
When solving for multiple variables, it can be more convenient to store the outputs in a structure array than in separate variables. The solve
function returns a structure when you specify a single output argument and multiple outputs exist.
Solve a system of equations to return the solutions in a structure array.
syms u v eqns = [2*u + v == 0, u - v == 1]; S = solve(eqns,[u v])
S = struct with fields:
u: 1/3
v: -2/3
Access the solutions by addressing the elements of the structure.
Using a structure array allows you to conveniently substitute solutions into other expressions.
Use the subs
function to substitute the solutions S
into other expressions.
expr1 = u^2; e1 = subs(expr1,S)
expr2 = 3*v + u; e2 = subs(expr2,S)
If solve
returns an empty object, then no solutions exist.
eqns = [3*u+2, 3*u+1]; S = solve(eqns,u)
Solve Inequalities
The solve
function can solve inequalities and return solutions that satisfy the inequalities. Solve the following inequalities.
x>0
y>0
x2+y2+xy<1
Set 'ReturnConditions'
to true
to return any parameters in the solution and conditions on the solution.
syms x y eqn1 = x > 0; eqn2 = y > 0; eqn3 = x^2 + y^2 + x*y < 1; eqns = [eqn1 eqn2 eqn3]; S = solve(eqns,[x y],'ReturnConditions',true); S.x
The parameters u
and v
do not exist in MATLAB® workspace and must be accessed using S.parameters
.
Check if the values u = 7/2
and v = 1/2
satisfy the condition using subs
and isAlways
.
condWithValues = subs(S.conditions, S.parameters, [7/2,1/2]); isAlways(condWithValues)
isAlways
returns logical 1 (true
) indicating that these values satisfy the condition. Substitute these parameter values into S.x
and S.y
to find a solution for x
and y
.
xSol = subs(S.x, S.parameters, [7/2,1/2])
ySol = subs(S.y, S.parameters, [7/2,1/2])
Solve Multivariate Equations and Assign Outputs to Variables
Solve the system of equations.
2u2+v2=0
u-v=1
When solving for more than one variable, the order in which you specify the variables defines the order in which the solver returns the solutions. Assign the solutions to variables solv
and solu
by specifying the variables explicitly. The solver returns an array of solutions for each variable.
syms u v eqns = [2*u^2 + v^2 == 0, u - v == 1]; vars = [v u]; [solv, solu] = solve(eqns,vars)
solv =(-23-2 i3-23+2 i3)
Entries with the same index form the pair of solutions.
solutions =(-23-2 i313-2 i3-23+2 i313+2 i3)
Use Parameters and Conditions to Refine Solution
Return the complete solution of an equation with parameters and conditions of the solution by specifying 'ReturnConditions'
as true
.
Solve the equation sin(x)=0. Provide two additional output variables for output arguments parameters
and conditions
.
syms x eqn = sin(x) == 0; [solx,parameters,conditions] = solve(eqn,x,'ReturnConditions',true)
The solution πk contains the parameter k, where k must be an integer. The variable k does not exist in the MATLAB® workspace and must be accessed using parameters
.
Restrict the solution to 0<x<2π. Find a valid value of k for this restriction. Assume the condition, conditions
, and use solve
to find k. Substitute the value of k found into the solution for x.
assume(conditions) restriction = [solx > 0, solx < 2*pi]; solk = solve(restriction,parameters)
valx = subs(solx,parameters,solk)
Alternatively, determine the solution for x by choosing a value of k. Check if the value chosen satisfies the condition on k using isAlways
.
Check if k=4 satisfies the condition on k.
condk4 = subs(conditions,parameters,4); isAlways(condk4)
isAlways
returns logical 1(true
), meaning that 4 is a valid value for k. Substitute k with 4 to obtain a solution for x. Use vpa
to obtain a numeric approximation.
valx = subs(solx,parameters,4)
ans = 12.566370614359172953850573533118
Shorten Result with Simplification Rules
Solve the equation exp(log(x)log(3x))=4.
By default, solve
does not apply simplifications that are not valid for all values of x. In this case, the solver does not assume that x is a positive real number, so it does not apply the logarithmic identity log(3x)=log(3)+log(x). As a result, solve
cannot solve the equation symbolically.
syms x
eqn = exp(log(x)*log(3*x)) == 4;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(fullfile(docroot, 'symbolic/vpasolve.html'))">vpasolve</a>.
S = -14.009379055223370038369334703094-2.9255310052111119036668717988769 i
Set 'IgnoreAnalyticConstraints'
to true
to apply simplification rules that might allow solve
to find a solution. For details, see Algorithms.
S = solve(eqn,x,'IgnoreAnalyticConstraints',true)
S =(3 e-log(256)+log(3)2233 elog(256)+log(3)223)
solve
applies simplifications that allow the solver to find a solution. The mathematical rules applied when performing simplifications are not always valid in general. In this example, the solver applies logarithmic identities with the assumption that x is a positive real number. Therefore, the solutions found in this mode should be verified.
Ignore Assumptions on Variables
The sym
and syms
functions let you set assumptions for symbolic variables.
Assume that the variable x
is positive.
When you solve an equation for a variable under assumptions, the solver only returns solutions consistent with the assumptions. Solve this equation for x
.
eqn = x^2 + 5*x - 6 == 0; S = solve(eqn,x)
Allow solutions that do not satisfy the assumptions by setting 'IgnoreProperties'
to true
.
S = solve(eqn,x,'IgnoreProperties',true)
For further computations, clear the assumption that you set on the variable x
by recreating it using syms
.
Solve Polynomial Equations of High Degree
When you solve a polynomial equation, the solver might use root
to return the solutions. Solve a third-degree polynomial.
syms x a eqn = x^3 + x^2 + a == 0; solve(eqn, x)
ans =(root(z3+z2+a,z,1)root(z3+z2+a,z,2)root(z3+z2+a,z,3))
Try to get an explicit solution for such equations by calling the solver with 'MaxDegree'
. The option specifies the maximum degree of polynomials for which the solver tries to return explicit solutions. The default value is 2
. Increasing this value, you can get explicit solutions for higher order polynomials.
Solve the same equations for explicit solutions by increasing the value of 'MaxDegree'
to 3
.
S = solve(eqn, x, 'MaxDegree', 3)
S =(19 σ1+σ1-13-118 σ1-σ12-13-3 19 σ1-σ1 i2-118 σ1-σ12-13+3 19 σ1-σ1 i2)where σ1=a2+1272-1729-a2-1271/3
Return One Solution
Solve the equation sin(x)+cos(2x)=1.
Instead of returning an infinite set of periodic solutions, the solver picks three solutions that it considers to be the most practical.
syms x
eqn = sin(x) + cos(2*x) == 1;
S = solve(eqn,x)
Choose only one solution by setting 'PrincipalValue'
to true
.
S1 = solve(eqn,x,'PrincipalValue',true)
Input Arguments
collapse all
eqn
— Equation to solve
symbolic expression | symbolic equation
Equation to solve, specified as a symbolic expression or symbolic equation. The
relation operator ==
defines symbolic equations. If
eqn
is a symbolic expression (without the right side), the solver
assumes that the right side is 0, and solves the equation eqn ==
.
0
var
— Variable for which you solve equation
symbolic variable
Variable for which you solve an equation, specified as a symbolic variable. By
default, solve
uses the variable determined by symvar
.
eqns
— System of equations
symbolic expressions | symbolic equations
System of equations, specified as symbolic expressions or symbolic equations. If any
elements of eqns
are symbolic expressions (without the right side),
solve
equates the element to 0
.
vars
— Variables for which you solve an equation or system of equations
symbolic vector | symbolic matrix
Variables for which you solve an equation or system of equations, specified as a
symbolic vector or symbolic matrix. By default, solve
uses the
variables determined by symvar
.
The order in which you specify these variables defines the order in which the solver
returns the solutions.
Name-Value Arguments
Example: 'Real',true
specifies that the solver returns real
solutions.
Real
— Flag for returning only real solutions
false
(default) | true
Flag for returning only real solutions, specified as the comma-separated pair
consisting of 'Real'
and one of these values.
false |
Return all solutions. |
true |
Return only those solutions for which every subexpression of the original equation represents a real number. This option also assumes that all symbolic parameters of an equation represent real numbers. |
See Solve Polynomial and Return Real Solutions.
ReturnConditions
— Flag for returning parameters and conditions
false
(default) | true
Flag for returning parameters in solution and conditions under which the solution
is true, specified as the comma-separated pair consisting of
'ReturnConditions'
and one of these values.
false |
Do not return parameterized solutions and the conditions under which the solution holds. The solve function replaces parameterswith appropriate values. |
true |
Return the parameters in the solution and the conditions under which the solution holds. For a call with a single output variable, solve returns a structure with the fieldsparameters and conditions . Formultiple output variables, solve assigns the parametersand conditions to the last two output variables. This behavior means that the number of output variables must be equal to the number of variables to solve for plus two. |
See Solve Inequalities.
Example: [v1, v2, params, conditions] = solve(sin(x) +y == 0,y^2 ==
returns the parameters in
3,'ReturnConditions',true)
params
and conditions in
conditions
.
IgnoreAnalyticConstraints
— Simplification rules applied to expressions and equations
false
(default) | true
Simplification rules applied to expressions and equations, specified as the
comma-separated pair consisting of 'IgnoreAnalyticConstraints'
and
one of these values.
false |
Use strict simplification rules. |
true |
Apply purely algebraic simplifications to expressions and equations. Setting IgnoreAnalyticConstraints totrue can give you simpler solutions, which could lead toresults not generally valid. In other words, this option applies mathematical identities that are convenient, but the results might not hold for all possible values of the variables. In some cases, it also enables solve to solve equations and systems that cannot besolved otherwise. For details, see Algorithms. |
See Shorten Result with Simplification Rules.
IgnoreProperties
— Flag for returning solutions inconsistent with properties of variables
false
(default) | true
Flag for returning solutions inconsistent with the properties of variables,
specified as the comma-separated pair consisting of
'IgnoreProperties'
and one of these values.
false |
Do not include solutions inconsistent with the properties of variables. |
true |
Include solutions inconsistent with the properties of variables. |
See Ignore Assumptions on Variables.
MaxDegree
— Maximum degree of polynomial equations for which solver uses explicit formulas
2
(default) | positive integer smaller than 5
Maximum degree of polynomial equations for which solver uses explicit formulas,
specified as a positive integer smaller than 5. The solver does not use explicit
formulas that involve radicals when solving polynomial equations of a degree larger
than the specified value.
See Solve Polynomial Equations of High Degree.
PrincipalValue
— Flag for returning one solution
false
(default) | true
Flag for returning one solution, specified as the comma-separated pair consisting
of 'PrincipalValue'
and one of these values.
false |
Return all solutions. |
true |
Return only one solution. If an equation or a system of equations does not have a solution, the solver returns an empty symbolic object. |
See Return One Solution.
Output Arguments
collapse all
S
— Solutions of equation
symbolic array
Solutions of an equation, returned as a symbolic array. The size of a symbolic array
corresponds to the number of the solutions.
Y
— Solutions of system of equations
structure
Solutions of a system of equations, returned as a structure. The number of fields in
the structure correspond to the number of independent variables in a system. If
'ReturnConditions'
is set to true
, the
solve
function returns two additional fields that contain the
parameters in the solution, and the conditions under which the solution is true.
y1,...,yN
— Solutions of system of equations
symbolic variables
Solutions of a system of equations, returned as symbolic variables. The number of
output variables or symbolic arrays must be equal to the number of independent variables
in a system. If you explicitly specify independent variables vars
,
then the solver uses the same order to return the solutions. If you do not specify
vars
, the toolbox sorts independent variables alphabetically, and
then assigns the solutions for these variables to the output variables.
parameters
— Parameters in solution
vector of generated parameters
Parameters in a solution, returned as a vector of generated parameters. This output
argument is only returned if ReturnConditions
is
true
. If a single output argument is provided,
parameters
is returned as a field of a structure. If multiple
output arguments are provided, parameters
is returned as the
second-to-last output argument. The generated parameters do not appear in the
MATLAB® workspace. They must be accessed using
parameters
.
Example: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions',
returns the parameter
true)k
in the argument
params
.
conditions
— Conditions under which solutions are valid
vector of symbolic expressions
Conditions under which solutions are valid, returned as a vector of symbolic
expressions. This output argument is only returned if
ReturnConditions
is true
. If a single output
argument is provided, conditions
is returned as a field of a
structure. If multiple output arguments are provided, conditions
is
returned as the last output argument.
Example: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions',
returns the condition
true)in(k, 'integer')
in
conditions
. The solution in solx
is valid only
under this condition.
Tips
-
If
solve
cannot find a solution and
ReturnConditions
isfalse
, the
solve
function internally calls the numeric solver
vpasolve
that tries to find a numeric solution. For polynomial
equations and systems without symbolic parameters, the numeric solver returns all
solutions. For nonpolynomial equations and systems without symbolic parameters, the
numeric solver returns only one solution (if a solution exists). -
If
solve
cannot find a solution and
ReturnConditions
istrue
,
solve
returns an empty solution with a warning. If no solutions
exist,solve
returns an empty solution without a warning. -
If the solution contains parameters and
ReturnConditions
is
true
,solve
returns the parameters in the
solution and the conditions under which the solutions are true. If
ReturnConditions
isfalse
, the
solve
function either chooses values of the parameters and returns
the corresponding results, or returns parameterized solutions without choosing particular
values. In the latter case,solve
also issues a warning indicating
the values of parameters in the returned solutions. -
If a parameter does not appear in any condition, it means the parameter can take any
complex value. -
The output of
solve
can contain parameters from the input
equations in addition to parameters introduced bysolve
. -
Parameters introduced by
solve
do not appear in the MATLAB workspace. They must be accessed using the output argument that contains
them. Alternatively, to use the parameters in the MATLAB workspace usesyms
to initialize the parameter. For
example, if the parameter isk
, usesyms k
. -
The variable names
parameters
andconditions
are
not allowed as inputs tosolve
. -
To solve differential equations, use the
dsolve
function. -
When solving a system of equations, always assign the result to output arguments.
Output arguments let you access the values of the solutions of a system. -
MaxDegree
only accepts positive integers smaller than 5 because, in
general, there are no explicit expressions for the roots of polynomials of degrees higher
than 4. -
The output variables
y1,...,yN
do not specify the variables for
whichsolve
solves equations or systems. If
y1,...,yN
are the variables that appear in
eqns
, then there is no guarantee that
solve(eqns)
will assign the solutions to
y1,...,yN
using the correct order. Thus, when you run
[b,a] = solve(eqns)
, you might get the solutions for
a
assigned tob
and vice versa.To ensure the order of the returned solutions, specify the variables
vars
. For example, the call[b,a] =
assigns the solutions for
solve(eqns,b,a)a
to
a
and the solutions forb
to
b
.
Algorithms
When you use IgnoreAnalyticConstraints
, the solver applies some of
these rules to the expressions on both sides of an equation.
-
log(a) +
log(b) = log(a·b) for all values of a and b. In
particular, the following equality is valid for all values of a,
b, and c:(a·b)c = ac·bc.
-
log(ab) = b·log(a) for all values of a and b. In
particular, the following equality is valid for all values of a,
b, and c:(ab)c = ab·c.
-
If f and g are standard mathematical functions
and f(g(x)) = x for all small positive numbers, f(g(x)) = x is assumed to be valid for all complex values x. In
particular:-
log(ex) = x
-
asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
-
asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
-
Wk(x·ex) = x for all branch indices k of the Lambert W function.
-
-
The solver can multiply both sides of an equation by any expression except
0
. -
The solutions of polynomial equations must be complete.
Version History
Introduced before R2006a
Symbolic Math Toolbox™ offers both symbolic and numeric equation
solvers. This topic shows you how to solve an equation symbolically
using the symbolic solver solve
. To compare symbolic
and numeric solvers, see Select Numeric or Symbolic Solver.
-
Solve an Equation
-
Return the Full Solution to an Equation
-
Work with the Full Solution, Parameters, and Conditions Returned
by solve -
Visualize and Plot Solutions Returned by solve
-
Simplify Complicated Results and Improve Performance
Solve an Equation
If eqn
is an equation, solve(eqn,
solves
x)eqn
for the symbolic variable x
.
Use the ==
operator to specify the familiar
quadratic equation and solve it using solve
.
syms a b c x eqn = a*x^2 + b*x + c == 0; solx = solve(eqn, x)
solx = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a)
solx
is a symbolic vector containing the
two solutions of the quadratic equation. If the input eqn
is
an expression and not an equation, solve
solves
the equation eqn == 0
.
To solve for a variable other than x
, specify
that variable instead. For example, solve eqn
for b
.
If you do not specify a variable, solve
uses symvar
to
select the variable to solve for. For example, solve(eqn)
solves eqn
for x
.
Return the Full Solution to an Equation
solve
does not automatically return all
solutions of an equation. Solve the equation cos(x) == -sin(x)
.
The solve
function returns one of many solutions.
syms x solx = solve(cos(x) == -sin(x), x)
To return all solutions along with the parameters in the solution
and the conditions on the solution, set the ReturnConditions
option
to true
. Solve the same equation for the full
solution. Provide three output variables: for the solution to x
,
for the parameters in the solution, and for the conditions on the
solution.
syms x [solx, param, cond] = solve(cos(x) == -sin(x), x, 'ReturnConditions', true)
solx = pi*k - pi/4 param = k cond = in(k, 'integer')
solx
contains the solution for x
,
which is pi*k - pi/4
. The param
variable
specifies the parameter in the solution, which is k
.
The cond
variable specifies the condition in(k,
on the solution, which means
'integer')k
must
be an integer. Thus, solve
returns a periodic
solution starting at pi/4
which repeats at intervals
of pi*k
, where k
is an integer.
Work with the Full Solution, Parameters, and Conditions Returned by solve
You can use the solutions, parameters, and conditions returned
by solve
to find solutions within an interval
or under additional conditions.
To find values of x
in the interval -2*pi<x<2*pi
,
solve solx
for k
within that
interval under the condition cond
. Assume the condition cond
using assume
.
assume(cond) solk = solve(-2*pi<solx, solx<2*pi, param)
To find values of x
corresponding to these
values of k
, use subs
to substitute
for k
in solx
.
xvalues = subs(solx, solk)
xvalues = -(5*pi)/4 -pi/4 (3*pi)/4 (7*pi)/4
To convert these symbolic values into numeric values for use
in numeric calculations, use vpa
.
xvalues = -3.9269908169872415480783042290994 -0.78539816339744830961566084581988 2.3561944901923449288469825374596 5.4977871437821381673096259207391
Visualize and Plot Solutions Returned by solve
The previous sections used solve
to solve
the equation cos(x) == -sin(x)
. The solution to
this equation can be visualized using plotting functions such as fplot
and scatter
.
Plot both sides of equation cos(x) == -sin(x)
.
fplot(cos(x)) hold on grid on fplot(-sin(x)) title('Both sides of equation cos(x) = -sin(x)') legend('cos(x)','-sin(x)','Location','best','AutoUpdate','off')
Calculate the values of the functions at the values of x
,
and superimpose the solutions as points using scatter
.
yvalues =(-0.707106781186547524400844362104850.70710678118654752440084436210485-0.707106781186547524400844362104850.70710678118654752440084436210485)
scatter(xvalues, yvalues)
As expected, the solutions appear at the intersection of the
two plots.
Simplify Complicated Results and Improve Performance
If results look complicated, solve
is stuck,
or if you want to improve performance, see, Troubleshoot Equation Solutions from solve Function.
Related Topics
- Solve System of Linear Equations
- Solve Differential Equation
- Solve Differential Algebraic Equations (DAEs)
solve
Уравнения и системный решатель
Поддержка вектора символов или входных параметров строки была удалена. Вместо этого используйте syms
объявить переменные и входные параметры замены, такие как solve('2*x == 1','x')
с solve(2*x == 1,x)
.
Синтаксис
Описание
пример
решает уравнение S
= solve(eqn
,var
)eqn
для переменной var
. Если вы не задаете var
, symvar
функция определяет переменную, чтобы решить для. Например, solve(x + 1 == 2, x)
решает уравнение x + 1 = 2 для x.
пример
дополнительные опции использования заданы одним или несколькими S
= solve(eqn
,var
,Name,Value
)Name,Value
парные аргументы.
пример
решает систему уравнений Y
= solve(eqns
,vars
)eqns
для переменных vars
и возвращает структуру, которая содержит решения. Если вы не задаете vars
, solve
использование symvar
найти, что переменные решают для. В этом случае, количество переменных это symvar
находки равны количеству уравнений eqns
.
пример
дополнительные опции использования заданы одним или несколькими Y
= solve(eqns
,vars
,Name,Value
)Name,Value
парные аргументы.
пример
[
решает систему уравнений y1,...,yN
] = solve(eqns
,vars
)eqns
для переменных vars
. Решения присвоены переменным y1,...,yN
. Если вы не задаете переменные, solve
использование symvar
найти, что переменные решают для. В этом случае, количество переменных это symvar
находки равны количеству выходных аргументов N
.
[
дополнительные опции использования заданы одним или несколькими y1,...,yN
] = solve(eqns
,vars
,Name,Value
)Name,Value
парные аргументы.
пример
[
возвращает дополнительные аргументы y1,...,yN
,parameters
,conditions
]
= solve(eqns
,vars
,'ReturnConditions
',true)parameters
и conditions
это задает параметры в решении и условиях на решении.
Примеры
свернуть все
Решите квадратное уравнение
Решите квадратное уравнение, не задавая переменную, чтобы решить для. solve
выбирает x
возвратить решение.
syms a b c x eqn = a*x^2 + b*x + c == 0
S =(-b+b2-4 a c2 a-b-b2-4 a c2 a)
Задайте переменную, чтобы решить для и решить квадратное уравнение для a
.
Решите полином и возвратите действительные решения
Решите полином пятой степени. Это имеет пять решений.
syms x
eqn = x^5 == 3125;
S = solve(eqn,x)
S =(5-σ1-54-5 2 5-5 i4-σ1-54+5 2 5-5 i4σ1-54-5 2 5+5 i4σ1-54+5 2 5+5 i4)where σ1=5 54
Возвратите только действительные решения установкой 'Real'
опция к true
. Единственными действительными решениями этого уравнения является 5
.
S = solve(eqn,x,'Real',true)
Численно решите уравнения
Когда solve
не может символически решить уравнение, оно пытается найти числовое решение с помощью vpasolve
. vpasolve
функция возвращает первое найденное решение.
Попытайтесь решить следующее уравнение. solve
возвращает числовое решение, потому что оно не может найти символьное решение.
syms x
eqn = sin(x) == x^2 - 1;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(fullfile(docroot, 'symbolic/vpasolve.html'))">vpasolve</a>.
S = -0.63673265080528201088799090383828
Постройте левые и правые стороны уравнения. Заметьте, что уравнение также имеет положительное решение.
fplot([lhs(eqn) rhs(eqn)], [-2 2])
Найдите другое решение путем прямого вызова числового решателя vpasolve
и определение интервала.
V = vpasolve(eqn,x,[0 2])
V = 1.4096240040025962492355939705895
Решите многомерные уравнения и присвойте Выходные параметры структуре
При решении для нескольких переменных может быть более удобно сохранить выходные параметры в массиве структур, чем в отдельных переменных. solve
функция возвращает структуру, когда вы задаете один выходной аргумент, и существуют несколько выходных параметров.
Решите систему уравнений, чтобы возвратить решения в массиве структур.
syms u v eqns = [2*u + v == 0, u - v == 1]; S = solve(eqns,[u v])
S = struct with fields:
u: 1/3
v: -2/3
Доступ к решениям путем обращения к элементам структуры.
Используя массив структур позволяет вам удобно заменять решениями в другие выражения.
Используйте subs
функционируйте, чтобы заменить решениями S
в другие выражения.
expr1 = u^2; e1 = subs(expr1,S)
expr2 = 3*v + u; e2 = subs(expr2,S)
Если solve
возвращает пустой объект, затем никакие решения не существуют.
eqns = [3*u+2, 3*u+1]; S = solve(eqns,u)
Решите неравенства
solve
функция может решить неравенства и возвратить решения, которые удовлетворяют неравенствам. Решите следующие неравенства.
x>0
y>0
x2+y2+xy<1
Установите 'ReturnConditions'
к true
возвратить любые параметры в решении и условиях на решении.
syms x y eqn1 = x > 0; eqn2 = y > 0; eqn3 = x^2 + y^2 + x*y < 1; eqns = [eqn1 eqn2 eqn3]; S = solve(eqns,[x y],'ReturnConditions',true); S.x
Параметры u
и v
не существуйте в рабочей области MATLAB®, и должен быть получен доступ с помощью S.parameters
.
Проверяйте если значения u = 7/2
и v = 1/2
удовлетворите условию с помощью subs
и isAlways
.
condWithValues = subs(S.conditions, S.parameters, [7/2,1/2]); isAlways(condWithValues)
isAlways
возвращает логическую единицу (true
) указание, что эти значения удовлетворяют условию. Замените этими значениями параметров в S.x
и S.y
найти решение для x
и y
.
xSol = subs(S.x, S.parameters, [7/2,1/2])
ySol = subs(S.y, S.parameters, [7/2,1/2])
Решите многомерные уравнения и присвойте Выходные параметры переменным
Решите систему уравнений.
2u2+v2=0
u-v=1
При решении больше чем для одной переменной порядок, в котором вы задаете переменные, задает порядок, в котором решатель возвращает решения. Присвойте решения переменных solv
и solu
путем определения переменных явным образом. Решатель возвращает массив решений для каждой переменной.
syms u v eqns = [2*u^2 + v^2 == 0, u - v == 1]; vars = [v u]; [solv, solu] = solve(eqns,vars)
solv =(-23-2 i3-23+2 i3)
Записи с тем же индексом формируют пару решений.
solutions =(-23-2 i313-2 i3-23+2 i313+2 i3)
Используйте параметры и условия совершенствовать решение
Возвратите полное решение уравнения параметрами и условиями решения путем определения 'ReturnConditions'
как true
.
Решите уравнение sin(x)=0. Обеспечьте две дополнительных выходных переменные для выходных аргументов parameters
и conditions
.
syms x eqn = sin(x) == 0; [solx,parameters,conditions] = solve(eqn,x,'ReturnConditions',true)
Решение πk содержит параметр k, где k должно быть целое число. Переменная k не существует в рабочем пространстве MATLAB и должен быть получен доступ с помощью parameters
.
Ограничьте решение 0<x<2π. Найдите допустимое значение k для этого ограничения. Примите условие, conditions
, и используйте solve
найти k. Замените значением k найденный в решение для x.
assume(conditions) restriction = [solx > 0, solx < 2*pi]; solk = solve(restriction,parameters)
valx = subs(solx,parameters,solk)
В качестве альтернативы определите решение для x путем выбора значения k. Проверяйте, удовлетворяет ли выбранное значение условию на k использование isAlways
.
Проверяйте если k=4 удовлетворяет условию на k.
condk4 = subs(conditions,parameters,4); isAlways(condk4)
isAlways
возвращает логическую единицу (true
), подразумевать, что 4 допустимое значение для k. Замена k с 4, чтобы получить решение для x. Используйте vpa
получить числовое приближение.
valx = subs(solx,parameters,4)
ans = 12.566370614359172953850573533118
Сократите результат с правилами упрощения
Решите уравнение exp(log(x)log(3x))=4.
По умолчанию, solve
не применяет упрощения, которые не допустимы для всех значений x. В этом случае решатель не принимает это x положительное вещественное число, таким образом, оно не применяет логарифмическую идентичность log(3x)=log(3)+log(x). В результате solve
не может решить уравнение символически.
syms x
eqn = exp(log(x)*log(3*x)) == 4;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(fullfile(docroot, 'symbolic/vpasolve.html'))">vpasolve</a>.
S = -14.009379055223370038369334703094-2.9255310052111119036668717988769 i
Установите 'IgnoreAnalyticConstraints'
к true
применять правила упрощения, которые могут позволить solve
найти решение. Для получения дополнительной информации см. Алгоритмы.
S = solve(eqn,x,'IgnoreAnalyticConstraints',true)
S =(3 e-log(256)+log(3)2233 elog(256)+log(3)223)
solve
применяет упрощения, которые позволяют решателю находить решение. Математические правила применялись, когда выполняющие упрощения не всегда допустимы в целом. В этом примере решатель применяет логарифмические тождества учитывая, что x положительное вещественное число. Поэтому решения, найденные в этом режиме, должны быть проверены.
Проигнорируйте предположения на переменных
sym
и syms
функции позволяют вам установить предположения для символьных переменных.
Примите что переменная x
положительно.
Когда вы решаете уравнение для переменной под предположениями, решатель только возвращает решения, сопоставимые с предположениями. Решите это уравнение для x
.
eqn = x^2 + 5*x - 6 == 0; S = solve(eqn,x)
Позвольте решения, которые не удовлетворяют предположениям установкой 'IgnoreProperties'
к true
.
S = solve(eqn,x,'IgnoreProperties',true)
Для дальнейших расчетов очистите предположение, что вы устанавливаете на переменной x
путем воссоздания его с помощью syms
.
Решите полиномиальные знатные уравнения
Когда вы решаете полиномиальное уравнение, решатель может использовать root
возвратить решения. Решите полином третьей степени.
syms x a eqn = x^3 + x^2 + a == 0; solve(eqn, x)
ans =(root(z3+z2+a,z,1)root(z3+z2+a,z,2)root(z3+z2+a,z,3))
Попытайтесь получить явное решение для таких уравнений путем вызова решателя с 'MaxDegree'
. Опция задает максимальную степень полиномов, для которых решатель пытается возвратить явные решения. Значением по умолчанию является 2
. Увеличивая это значение, можно получить явные решения для полиномов высшего порядка.
Решите те же уравнения для явных решений путем увеличения значения 'MaxDegree'
к 3
.
S = solve(eqn, x, 'MaxDegree', 3)
S =(19 σ1+σ1-13-118 σ1-σ12-13-3 19 σ1-σ1 i2-118 σ1-σ12-13+3 19 σ1-σ1 i2)where σ1=a2+1272-1729-a2-1271/3
Возвратите одно решение
Решите уравнение sin(x)+cos(2x)=1.
Вместо того, чтобы возвратить бесконечное множество периодических решений, решатель выбирает три решения, что он считает самым практическим.
syms x
eqn = sin(x) + cos(2*x) == 1;
S = solve(eqn,x)
Выберите только одно решение установкой 'PrincipalValue'
к true
.
S1 = solve(eqn,x,'PrincipalValue',true)
Входные параметры
свернуть все
eqn
— Уравнение, чтобы решить
символьное выражение | символьное уравнение
Уравнение, чтобы решить в виде символьного выражения или символьного уравнения. Оператор отношения ==
определяет символьные уравнения. Если eqn
символьное выражение (без правой стороны), решатель принимает, что правая сторона 0 и решает уравнение eqn == 0
.
var
— Переменная, для которой вы решаете уравнение
символьная переменная
Переменная, для которой вы решаете уравнение в виде символьной переменной. По умолчанию, solve
использует переменную, определенную symvar
.
eqns
Система уравнений
символьные выражения | символьные уравнения
Система уравнений в виде символьных выражений или символьных уравнений. Если любые элементы eqns
символьные выражения (без правой стороны), solve
приравнивает элемент к 0
.
vars
— Переменные, для которых вы решаете уравнение или систему уравнений
символьный вектор | символьная матрица
Переменные, для которых вы решаете уравнение или систему уравнений в виде символьного вектора или символьной матрицы. По умолчанию, solve
использует переменные, определенные symvar
.
Порядок, в котором вы задаете эти переменные, задает порядок, в котором решатель возвращает решения.
Аргументы name-value
Пример: 'Real',true
указывает, что решатель возвращает действительные решения.
Real
— Отметьте для возврата только действительных решений
false
(значение по умолчанию) | true
Отметьте для возврата только действительных решений в виде разделенной запятой пары, состоящей из 'Real'
и одно из этих значений.
false |
Возвратите все решения. |
true |
Возвратите только те решения, для которых каждое подвыражение исходного уравнения представляет вещественное число. Эта опция также принимает, что все символьные параметры уравнения представляют вещественные числа. |
Смотрите решают полином и возвращают действительные решения.
ReturnConditions
— Отметьте для возврата параметров и условий
false
(значение по умолчанию) | true
Отметьте для возврата параметров в решении и условиях, при которых решение верно в виде разделенной запятой пары, состоящей из 'ReturnConditions'
и одно из этих значений.
false |
Не возвращайте параметрированные решения и условия, при которых решение содержит. solve функционируйте заменяет параметры на соответствующие значения. |
true |
Возвратите параметры в решении и условиях, при которых решение содержит. Для вызова с одной выходной переменной, solve возвращает структуру с полями parameters и conditions . Для нескольких выходных переменных, solve присваивает параметры и условия к последним двум выходным переменным. Это поведение означает, что количество выходных переменных должно быть равно количеству переменных, чтобы решить для плюс два. |
Смотрите решают неравенства.
Пример: [v1, v2, params, conditions] = solve(sin(x) +y == 0,y^2 == 3,'ReturnConditions',true)
возвращает параметры в params
и условия в conditions
.
IgnoreAnalyticConstraints
— Правила упрощения применились к выражениям и уравнениям
false
(значение по умолчанию) | true
Правила упрощения применились к выражениям и уравнениям в виде разделенной запятой пары, состоящей из 'IgnoreAnalyticConstraints'
и одно из этих значений.
false |
Используйте строгие правила упрощения. |
true |
Примените чисто алгебраические упрощения в выражениях и уравнениях. Установка IgnoreAnalyticConstraints к true может дать вам простые решения, которые могли привести к результатам, не обычно допустимым. Другими словами, эта опция применяет математические тождества, которые удобны, но результаты не могут содержать для всех возможных значений переменных. В некоторых случаях это также включает solve решить уравнения и системы, которые не могут быть решены в противном случае. |
Смотрите сокращают результат с правилами упрощения.
IgnoreProperties
— Отметьте для возврата решений, противоречивых со свойствами переменных
false
(значение по умолчанию) | true
Отметьте для возврата решений, противоречивых со свойствами переменных в виде разделенной запятой пары, состоящей из 'IgnoreProperties'
и одно из этих значений.
false |
Не включайте решения, противоречивые со свойствами переменных. |
true |
Включайте решения, противоречивые со свойствами переменных. |
Смотрите игнорируют предположения на переменных.
MaxDegree
— Максимальная степень полиномиальных уравнений, для которых решатель использует явные формулы
2
(значение по умолчанию) | положительное целое число, меньшее, чем 5
Максимальная степень полиномиальных уравнений, для которых решатель использует явные формулы в виде положительного целого числа, меньшего, чем 5. Решатель не использует явные формулы, которые вовлекают радикалов при решении полиномиальных уравнений степени, больше, чем заданное значение.
Смотрите решают полиномиальные знатные уравнения.
PrincipalValue
— Отметьте для возврата одного решения
false
(значение по умолчанию) | true
Отметьте для возврата одного решения в виде разделенной запятой пары, состоящей из 'PrincipalValue'
и одно из этих значений.
false |
Возвратите все решения. |
true |
Возвратите только одно решение. Если уравнение или система уравнений не имеют решения, решатель возвращает пустой символьный объект. |
Смотрите возвращают одно решение.
Выходные аргументы
свернуть все
S
— Решения уравнения
символьный массив
Решения уравнения, возвращенного как символьный массив. Размер символьного массива соответствует количеству решений.
Y
— Решения системы уравнений
структура
Решения системы уравнений, возвращенной как структура. Количество полей в структуре соответствует количеству независимых переменных в системе. Если 'ReturnConditions'
установлен в true
, solve
функция возвращает два дополнительных поля, которые содержат параметры в решении и условия, при которых решение верно.
y1,...,yN
— Решения системы уравнений
символьные переменные
Решения системы уравнений, возвращенной как символьные переменные. Количество выходных переменных или символьных массивов должно быть равно количеству независимых переменных в системе. Если вы явным образом задаете независимые переменные vars
, затем решатель использует тот же порядок возвратить решения. Если вы не задаете vars
, независимые переменные видов тулбокса в алфавитном порядке, и затем присваивают решения для этих переменных к выходным переменным.
parameters
— Параметры в решении
вектор из сгенерированных параметров
Параметры в решении, возвращенном как вектор из сгенерированных параметров. Этот выходной аргумент только возвращен если ReturnConditions
true
. Если один выходной аргумент обеспечивается, parameters
возвращен как поле структуры. Если несколько выходных аргументов обеспечиваются, parameters
возвращен как предпоследний выходной аргумент. Сгенерированные параметры не появляются в MATLAB® рабочая область. К ним нужно получить доступ с помощью parameters
.
Пример: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions', true)
возвращает параметр k
в аргументе params
.
conditions
— Условия, при которых решения допустимы
вектор из символьных выражений
Условия, при которых решения допустимы, возвратились как вектор из символьных выражений. Этот выходной аргумент только возвращен если ReturnConditions
true
. Если один выходной аргумент обеспечивается, conditions
возвращен как поле структуры. Если несколько выходных аргументов обеспечиваются, conditions
возвращен как последний выходной аргумент.
Пример: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions', true)
возвращает условие in(k, 'integer')
в conditions
. Решение в solx
допустимо только при этом условии.
Советы
-
Если
solve
не может найти решение иReturnConditions
false
,solve
функционируйте внутренне вызывает числовой решательvpasolve
это пытается найти числовое решение. Для полиномиальных уравнений и систем без символьных параметров, числовой решатель возвращает все решения. Для неполиномиальных уравнений и систем без символьных параметров, числовой решатель возвращает только одно решение (если решение существует). -
Если
solve
не может найти решение иReturnConditions
true
,solve
возвращает пустое решение с предупреждением. Если никакие решения не существуют,solve
возвращает пустое решение без предупреждения. -
Если решение содержит параметры и
ReturnConditions
true
,solve
возвращает параметры в решении и условиях, при которых решения верны. ЕслиReturnConditions
false
,solve
функционируйте или выбирает значения параметров и возвращает соответствующие результаты или возвращает параметрированные решения, не выбирая особые значения. В последнем случае,solve
также выдает предупреждение, указывающее на значения параметров в возвращенных решениях. -
Если параметр не появляется ни в каком условии, это означает, что параметр может взять любое комплексное число.
-
Выход
solve
может содержать параметры от исходных уравнений в дополнение к параметрам, введеннымsolve
. -
Параметры, введенные
solve
не появляйтесь в рабочем пространстве MATLAB. К ним нужно получить доступ с помощью выходного аргумента, который содержит их. В качестве альтернативы использовать параметры в использовании рабочего пространства MATLABsyms
инициализировать параметр. Например, если параметром являетсяk
, используйтеsyms k
. -
Имена переменных
parameters
иconditions
не позволены как входные параметрыsolve
. -
Чтобы решить дифференциальные уравнения, используйте
dsolve
функция. -
При решении системы уравнений всегда присваивайте результат выходным аргументам. Выходные аргументы позволяют вам получить доступ к значениям решений системы.
-
MaxDegree
только принимает положительные целые числа, меньшие, чем 5 потому что, в целом, нет никаких явных выражений для корней полиномов степеней выше, чем 4. -
Выходные переменные
y1,...,yN
не задавайте переменные для которыйsolve
решает уравнения или системы. Еслиy1,...,yN
переменные, которые появляются вeqns
, затем нет никакой гарантии чтоsolve(eqns)
присвоит решенияy1,...,yN
использование правильного порядка. Таким образом, когда вы запускаете[b,a] = solve(eqns)
, вы можете получить решения дляa
присвоенныйb
и наоборот.Чтобы гарантировать порядок возвращенных решений, задайте переменные
vars
. Например, вызов[b,a] = solve(eqns,b,a)
присваивает решения дляa
кa
и решения дляb
кb
.
Алгоритмы
Когда вы используете IgnoreAnalyticConstraints
, решатель применяет эти правила к выражениям с обеих сторон уравнения.
-
регистрируйте (a) + журнал (b) = журнал (a · b) для всех значений a и b. В частности, следующее равенство допустимо для всех значений a, b и c:
A, B c = acBc.
-
журнал (ab) = b · регистрируйте (a) для всех значений a и b. В частности, следующее равенство допустимо для всех значений a, b и c:
Ab)c = ab·c.
-
Если f и g являются стандартными математическими функциями и f (g (x)) = x для всех маленьких положительных чисел, f (g (x)) = , x принят, чтобы быть допустимым для всех комплексных чисел x. В частности:
-
журнал (ex) = x
-
asin (sin (x)) = x, acos (cos (x)) = x, atan (tan (x)) = x
-
asinh (sinh (x)) = x, acosh (дубинка (x)) = x, atanh (tanh (x)) = x
-
Wk (x · ex) = x для всех индексов ветви k функции Ламберта В.
-
-
Решатель может умножить обе стороны уравнения по любому выражению кроме
0
. -
Решения полиномиальных уравнений должны быть завершены.
Представлено до R2006a
Solve optimization problem or equation problem
Syntax
Description
Use solve
to find the solution of an optimization problem
or equation problem.
example
sol
= solve(prob
)
solves the optimization problem or equation problem prob
.
example
sol
= solve(prob
,x0
)
solves prob
starting from the point or set of values
x0
.
example
sol
= solve(prob
,x0
,ms
)
solves prob
using the ms
multiple-start
solver. Use this syntax to search for a better solution than you obtain when not
using the ms
argument.
example
sol
= solve(___,Name,Value
)
modifies the solution process using one or more name-value pair arguments in
addition to the input arguments in previous syntaxes.
[
sol
,fval
] = solve(___)
also returns the objective function value at the solution using any of the input
arguments in previous syntaxes.
example
[
sol
,fval
,exitflag
,output
,lambda
] = solve(___)
also returns an exit flag describing the exit condition, an
output
structure containing additional information about the
solution process, and, for non-integer optimization problems, a Lagrange multiplier
structure.
Examples
collapse all
Solve Linear Programming Problem
Solve a linear programming problem defined by an optimization problem.
x = optimvar('x'); y = optimvar('y'); prob = optimproblem; prob.Objective = -x - y/3; prob.Constraints.cons1 = x + y <= 2; prob.Constraints.cons2 = x + y/4 <= 1; prob.Constraints.cons3 = x - y <= 2; prob.Constraints.cons4 = x/4 + y >= -1; prob.Constraints.cons5 = x + y >= 1; prob.Constraints.cons6 = -x + y <= 2; sol = solve(prob)
Solving problem using linprog. Optimal solution found.
sol = struct with fields:
x: 0.6667
y: 1.3333
Solve Nonlinear Programming Problem Using Problem-Based Approach
Find a minimum of the peaks
function, which is included in MATLAB®, in the region x2+y2≤4. To do so, create optimization variables x
and y
.
x = optimvar('x'); y = optimvar('y');
Create an optimization problem having peaks
as the objective function.
prob = optimproblem("Objective",peaks(x,y));
Include the constraint as an inequality in the optimization variables.
prob.Constraints = x^2 + y^2 <= 4;
Set the initial point for x
to 1 and y
to –1, and solve the problem.
x0.x = 1; x0.y = -1; sol = solve(prob,x0)
Solving problem using fmincon. Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
sol = struct with fields:
x: 0.2283
y: -1.6255
Unsupported Functions Require fcn2optimexpr
If your objective or nonlinear constraint functions are not entirely composed of elementary functions, you must convert the functions to optimization expressions using fcn2optimexpr
. See Convert Nonlinear Function to Optimization Expression and Supported Operations for Optimization Variables and Expressions.
To convert the present example:
convpeaks = fcn2optimexpr(@peaks,x,y); prob.Objective = convpeaks; sol2 = solve(prob,x0)
Solving problem using fmincon. Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
sol2 = struct with fields:
x: 0.2283
y: -1.6255
Copyright 2018–2020 The MathWorks, Inc.
Solve Mixed-Integer Linear Program Starting from Initial Point
Compare the number of steps to solve an integer programming problem both with and without an initial feasible point. The problem has eight integer variables and four linear equality constraints, and all variables are restricted to be positive.
prob = optimproblem; x = optimvar('x',8,1,'LowerBound',0,'Type','integer');
Create four linear equality constraints and include them in the problem.
Aeq = [22 13 26 33 21 3 14 26 39 16 22 28 26 30 23 24 18 14 29 27 30 38 26 26 41 26 28 36 18 38 16 26]; beq = [ 7872 10466 11322 12058]; cons = Aeq*x == beq; prob.Constraints.cons = cons;
Create an objective function and include it in the problem.
f = [2 10 13 17 7 5 7 3]; prob.Objective = f*x;
Solve the problem without using an initial point, and examine the display to see the number of branch-and-bound nodes.
[x1,fval1,exitflag1,output1] = solve(prob);
Solving problem using intlinprog. LP: Optimal objective value is 1554.047531. Cut Generation: Applied 8 strong CG cuts. Lower bound is 1591.000000. Branch and Bound: nodes total num int integer relative explored time (s) solution fval gap (%) 10000 0.42 0 - - 14739 0.58 1 2.154000e+03 2.593968e+01 18258 0.73 2 1.854000e+03 1.180593e+01 18673 0.75 2 1.854000e+03 1.563342e+00 18829 0.75 2 1.854000e+03 0.000000e+00 Optimal solution found. Intlinprog stopped because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 0. The intcon variables are integer within tolerance, options.IntegerTolerance = 1e-05.
For comparison, find the solution using an initial feasible point.
x0.x = [8 62 23 103 53 84 46 34]'; [x2,fval2,exitflag2,output2] = solve(prob,x0);
Solving problem using intlinprog. LP: Optimal objective value is 1554.047531. Cut Generation: Applied 8 strong CG cuts. Lower bound is 1591.000000. Relative gap is 59.20%. Branch and Bound: nodes total num int integer relative explored time (s) solution fval gap (%) 3627 0.20 2 2.154000e+03 2.593968e+01 5844 0.29 3 1.854000e+03 1.180593e+01 6204 0.31 3 1.854000e+03 1.455526e+00 6400 0.32 3 1.854000e+03 0.000000e+00 Optimal solution found. Intlinprog stopped because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 0. The intcon variables are integer within tolerance, options.IntegerTolerance = 1e-05.
fprintf('Without an initial point, solve took %d steps.nWith an initial point, solve took %d steps.',output1.numnodes,output2.numnodes)
Without an initial point, solve took 18829 steps. With an initial point, solve took 6400 steps.
Giving an initial point does not always improve the problem. For this problem, using an initial point saves time and computational steps. However, for some problems, an initial point can cause solve
to take more steps.
Specify Starting Points and Values for surrogateopt
, Problem-Based
For some solvers, you can pass the objective and constraint function values, if any, to solve
in the x0
argument. This can save time in the solver. Pass a vector of OptimizationValues
objects. Create this vector using the optimvalues
function.
The solvers that can use the objective function values are:
-
ga
-
gamultiobj
-
paretosearch
-
surrogateopt
The solvers that can use nonlinear constraint function values are:
-
paretosearch
-
surrogateopt
For example, minimize the peaks
function using surrogateopt
, starting with values from a grid of initial points. Create a grid from -10 to 10 in the x
variable, and –5/2
to 5/2
in the y
variable with spacing 1/2. Compute the objective function values at the initial points.
x = optimvar("x",LowerBound=-10,UpperBound=10); y = optimvar("y",LowerBound=-5/2,UpperBound=5/2); prob = optimproblem("Objective",peaks(x,y)); xval = -10:10; yval = (-5:5)/2; [x0x,x0y] = meshgrid(xval,yval); peaksvals = peaks(x0x,x0y);
Pass the values in the x0
argument by using optimvalues
. This saves time for solve
, as solve
does not need to compute the values. Pass the values as row vectors.
x0 = optimvalues(prob,'x',x0x(:)','y',x0y(:)',... "Objective",peaksvals(:)');
Solve the problem using surrogateopt
with the initial values.
[sol,fval,eflag,output] = solve(prob,x0,Solver="surrogateopt")
Solving problem using surrogateopt.
surrogateopt stopped because it exceeded the function evaluation limit set by 'options.MaxFunctionEvaluations'.
sol = struct with fields:
x: 0.2283
y: -1.6256
eflag = SolverLimitExceeded
output = struct with fields:
elapsedtime: 35.1571
funccount: 200
constrviolation: 0
ineq: [1x1 struct]
rngstate: [1x1 struct]
message: 'surrogateopt stopped because it exceeded the function evaluation limit set by ...'
solver: 'surrogateopt'
Minimize Nonlinear Function Using Multiple-Start Solver, Problem-Based
Find a local minimum of the peaks
function on the range -5≤x,y≤5 starting from the point [–1,2]
.
x = optimvar("x",LowerBound=-5,UpperBound=5); y = optimvar("y",LowerBound=-5,UpperBound=5); x0.x = -1; x0.y = 2; prob = optimproblem(Objective=peaks(x,y)); opts = optimoptions("fmincon",Display="none"); [sol,fval] = solve(prob,x0,Options=opts)
sol = struct with fields:
x: -3.3867
y: 3.6341
Try to find a better solution by using the GlobalSearch
solver. This solver runs fmincon
multiple times, which potentially yields a better solution.
ms = GlobalSearch; [sol2,fval2] = solve(prob,x0,ms)
Solving problem using GlobalSearch. GlobalSearch stopped because it analyzed all the trial points. All 15 local solver runs converged with a positive local solver exit flag.
sol2 = struct with fields:
x: 0.2283
y: -1.6255
GlobalSearch
finds a solution with a better (lower) objective function value. The exit message shows that fmincon
, the local solver, runs 15 times. The returned solution has an objective function value of about –6.5511, which is lower than the value at the first solution, 1.1224e–07.
Solve Integer Programming Problem with Nondefault Options
Solve the problem
minx(-3×1-2×2-x3)subjectto{x3binaryx1,x2≥0x1+x2+x3≤74×1+2×2+x3=12
without showing iterative display.
x = optimvar('x',2,1,'LowerBound',0); x3 = optimvar('x3','Type','integer','LowerBound',0,'UpperBound',1); prob = optimproblem; prob.Objective = -3*x(1) - 2*x(2) - x3; prob.Constraints.cons1 = x(1) + x(2) + x3 <= 7; prob.Constraints.cons2 = 4*x(1) + 2*x(2) + x3 == 12; options = optimoptions('intlinprog','Display','off'); sol = solve(prob,'Options',options)
sol = struct with fields:
x: [2x1 double]
x3: 1
Examine the solution.
Use intlinprog
to Solve a Linear Program
Force solve
to use intlinprog
as the solver for a linear programming problem.
x = optimvar('x'); y = optimvar('y'); prob = optimproblem; prob.Objective = -x - y/3; prob.Constraints.cons1 = x + y <= 2; prob.Constraints.cons2 = x + y/4 <= 1; prob.Constraints.cons3 = x - y <= 2; prob.Constraints.cons4 = x/4 + y >= -1; prob.Constraints.cons5 = x + y >= 1; prob.Constraints.cons6 = -x + y <= 2; sol = solve(prob,'Solver', 'intlinprog')
Solving problem using intlinprog. LP: Optimal objective value is -1.111111. Optimal solution found. No integer variables specified. Intlinprog solved the linear problem.
sol = struct with fields:
x: 0.6667
y: 1.3333
Return All Outputs
Solve the mixed-integer linear programming problem described in Solve Integer Programming Problem with Nondefault Options and examine all of the output data.
x = optimvar('x',2,1,'LowerBound',0); x3 = optimvar('x3','Type','integer','LowerBound',0,'UpperBound',1); prob = optimproblem; prob.Objective = -3*x(1) - 2*x(2) - x3; prob.Constraints.cons1 = x(1) + x(2) + x3 <= 7; prob.Constraints.cons2 = 4*x(1) + 2*x(2) + x3 == 12; [sol,fval,exitflag,output] = solve(prob)
Solving problem using intlinprog. LP: Optimal objective value is -12.000000. Optimal solution found. Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 0. The intcon variables are integer within tolerance, options.IntegerTolerance = 1e-05.
sol = struct with fields:
x: [2x1 double]
x3: 1
exitflag = OptimalSolution
output = struct with fields:
relativegap: 0
absolutegap: 0
numfeaspoints: 1
numnodes: 0
constrviolation: 0
message: 'Optimal solution found....'
solver: 'intlinprog'
For a problem without any integer constraints, you can also obtain a nonempty Lagrange multiplier structure as the fifth output.
View Solution with Index Variables
Create and solve an optimization problem using named index variables. The problem is to maximize the profit-weighted flow of fruit to various airports, subject to constraints on the weighted flows.
rng(0) % For reproducibility p = optimproblem('ObjectiveSense', 'maximize'); flow = optimvar('flow', ... {'apples', 'oranges', 'bananas', 'berries'}, {'NYC', 'BOS', 'LAX'}, ... 'LowerBound',0,'Type','integer'); p.Objective = sum(sum(rand(4,3).*flow)); p.Constraints.NYC = rand(1,4)*flow(:,'NYC') <= 10; p.Constraints.BOS = rand(1,4)*flow(:,'BOS') <= 12; p.Constraints.LAX = rand(1,4)*flow(:,'LAX') <= 35; sol = solve(p);
Solving problem using intlinprog. LP: Optimal objective value is 1027.472366. Heuristics: Found 1 solution using ZI round. Lower bound is 1027.233133. Relative gap is 0.00%. Optimal solution found. Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 0. The intcon variables are integer within tolerance, options.IntegerTolerance = 1e-05.
Find the optimal flow of oranges and berries to New York and Los Angeles.
[idxFruit,idxAirports] = findindex(flow, {'oranges','berries'}, {'NYC', 'LAX'})
orangeBerries = sol.flow(idxFruit, idxAirports)
orangeBerries = 2×2
0 980
70 0
This display means that no oranges are going to NYC
, 70 berries are going to NYC
, 980 oranges are going to LAX
, and no berries are going to LAX
.
List the optimal flow of the following:
Fruit Airports
----- --------
Berries NYC
Apples BOS
Oranges LAX
idx = findindex(flow, {'berries', 'apples', 'oranges'}, {'NYC', 'BOS', 'LAX'})
optimalFlow = sol.flow(idx)
optimalFlow = 1×3
70 28 980
This display means that 70 berries are going to NYC
, 28 apples are going to BOS
, and 980 oranges are going to LAX
.
Solve Nonlinear System of Equations, Problem-Based
To solve the nonlinear system of equations
exp(-exp(-(x1+x2)))=x2(1+x12)x1cos(x2)+x2sin(x1)=12
using the problem-based approach, first define x
as a two-element optimization variable.
Create the first equation as an optimization equality expression.
eq1 = exp(-exp(-(x(1) + x(2)))) == x(2)*(1 + x(1)^2);
Similarly, create the second equation as an optimization equality expression.
eq2 = x(1)*cos(x(2)) + x(2)*sin(x(1)) == 1/2;
Create an equation problem, and place the equations in the problem.
prob = eqnproblem; prob.Equations.eq1 = eq1; prob.Equations.eq2 = eq2;
Review the problem.
EquationProblem : Solve for: x eq1: exp((-exp((-(x(1) + x(2)))))) == (x(2) .* (1 + x(1).^2)) eq2: ((x(1) .* cos(x(2))) + (x(2) .* sin(x(1)))) == 0.5
Solve the problem starting from the point [0,0]
. For the problem-based approach, specify the initial point as a structure, with the variable names as the fields of the structure. For this problem, there is only one variable, x
.
x0.x = [0 0]; [sol,fval,exitflag] = solve(prob,x0)
Solving problem using fsolve. Equation solved. fsolve completed because the vector of function values is near zero as measured by the value of the function tolerance, and the problem appears regular as measured by the gradient.
sol = struct with fields:
x: [2x1 double]
fval = struct with fields:
eq1: -2.4070e-07
eq2: -3.8255e-08
exitflag = EquationSolved
View the solution point.
Input Arguments
collapse all
prob
— Optimization problem or equation problem
OptimizationProblem
object | EquationProblem
object
Optimization problem or equation problem, specified as an OptimizationProblem
object or an EquationProblem
object. Create an optimization problem by using optimproblem
; create an equation problem by using eqnproblem
.
Warning
The problem-based approach does not support complex values in an objective function, nonlinear
equalities, or nonlinear inequalities. If a function calculation has
a complex value, even as an intermediate value, the final result
might be incorrect.
Example: prob = optimproblem; prob.Objective = obj; prob.Constraints.cons1 =
cons1;
Example: prob = eqnproblem; prob.Equations = eqs;
x0
— Initial point
structure | vector of OptimizationValues
objects
Initial point, specified as a structure with field names equal to the variable names in prob
.
For some Global Optimization Toolbox solvers, x0
can be a vector of OptimizationValues
objects representing multiple initial points. Create
the points using the optimvalues
function. These solvers are:
-
ga
(Global Optimization Toolbox),gamultiobj
(Global Optimization Toolbox),paretosearch
(Global Optimization Toolbox) andparticleswarm
(Global Optimization Toolbox). These solvers accept multiple starting points as
members of the initial population. -
MultiStart
(Global Optimization Toolbox). This solver accepts
multiple initial points for a local solver such as
fmincon
. -
surrogateopt
(Global Optimization Toolbox). This solver accepts multiple initial points to
help create an initial surrogate.
For an example using x0
with named index variables, see Create Initial Point for Optimization with Named Index Variables.
Example: If prob
has variables named x
and y
: x0.x = [3,2,17]; x0.y = [pi/3,2*pi/3]
.
Data Types: struct
ms
— Multiple start solver
MultiStart
object | GlobalSearch
object
Multiple start solver, specified as a MultiStart
(Global Optimization Toolbox) object or a GlobalSearch
(Global Optimization Toolbox) object. Create
ms
using the MultiStart
or
GlobalSearch
commands.
Currently, GlobalSearch
supports only the
fmincon
local solver, and
MultiStart
supports only the
fmincon
, fminunc
, and
lsqnonlin
local solvers.
Example: ms = MultiStart;
Example: ms =
GlobalSearch(FunctionTolerance=1e-4);
Name-Value Arguments
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN
, where Name
is
the argument name and Value
is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose
Name
in quotes.
Example: solve(prob,'Options',opts)
MinNumStartPoints
— Minimum number of start points for MultiStart
20 (default) | positive integer
Minimum number of start points for MultiStart
(Global Optimization Toolbox), specified as a
positive integer. This argument applies only when you call
solve
using the ms
argument. solve
uses all of the values in
x0
as start points. If
MinNumStartPoints
is greater than the number of
values in x0
, then solve
generates more start points uniformly at random within the problem
bounds. If a component is unbounded, solve
generates points using the default artificial bounds for
MultiStart
.
Example: solve(prob,x0,ms,MinNumStartPoints=50)
Data Types: double
Options
— Optimization options
object created by optimoptions
| options structure
Optimization options, specified as an object created by optimoptions
or an options
structure such as created by optimset
.
Internally, the solve
function calls a relevant
solver as detailed in the 'solver'
argument reference. Ensure that
options
is compatible with the solver. For
example, intlinprog
does not allow options to be a
structure, and lsqnonneg
does not allow options to be
an object.
For suggestions on options settings to improve an
intlinprog
solution or the speed of a solution,
see Tuning Integer Linear Programming. For linprog
, the
default 'dual-simplex'
algorithm is generally
memory-efficient and speedy. Occasionally, linprog
solves a large problem faster when the Algorithm
option is 'interior-point'
. For suggestions on
options settings to improve a nonlinear problem’s solution, see Optimization Options in Common Use: Tuning and Troubleshooting and Improve Results.
Example: options =
optimoptions('intlinprog','Display','none')
Solver
— Optimization solver
'intlinprog'
| 'linprog'
| 'lsqlin'
| 'lsqcurvefit'
| 'lsqnonlin'
| 'lsqnonneg'
| 'quadprog'
| 'fminbnd'
| 'fminunc'
| 'fmincon'
| 'fminsearch'
| 'fzero'
| 'fsolve'
| 'coneprog'
| 'ga'
| 'gamultiobj'
| 'paretosearch'
| 'patternsearch'
| 'particleswarm'
| 'surrogateopt'
| 'simulannealbnd'
Optimization solver, specified as the name of a listed solver. For optimization
problems, this table contains the available solvers for each problem type, including
solvers from Global Optimization Toolbox. Details for equation problems appear below the optimization solver
details.
For converting nonlinear problems with integer constraints using
prob2struct
, the resulting problem structure can depend on the
chosen solver. If you do not have a Global Optimization Toolbox license, you must specify the solver. See Integer Constraints in Nonlinear Problem-Based Optimization.
The default solver for each optimization problem type is listed here.
Problem Type | Default Solver |
---|---|
Linear Programming (LP) | linprog |
Mixed-Integer Linear Programming (MILP) | intlinprog |
Quadratic Programming (QP) | quadprog |
Second-Order Cone Programming (SOCP) | coneprog |
Linear Least Squares | lsqlin |
Nonlinear Least Squares | lsqnonlin |
Nonlinear Programming (NLP) |
|
Mixed-Integer Nonlinear Programming (MINLP) | ga (Global Optimization Toolbox) |
Multiobjective | gamultiobj (Global Optimization Toolbox) |
In this table, means the solver is available for the problem type,
x means the solver is not available.
Note
If you choose lsqcurvefit
as the solver for a least-squares
problem, solve
uses lsqnonlin
. The
lsqcurvefit
and lsqnonlin
solvers are
identical for solve
.
Caution
For maximization problems (prob.ObjectiveSense
is
"max"
or "maximize"
), do not specify a
least-squares solver (one with a name beginning lsq
). If you do,
solve
throws an error, because these solvers cannot
maximize.
For equation solving, this table contains the available solvers for each problem type.
In the table,
-
* indicates the default solver for the
problem type. -
Y indicates an available solver.
-
N indicates an unavailable solver.
Supported Solvers for Equations
Equation Type | lsqlin |
lsqnonneg |
fzero |
fsolve |
lsqnonlin |
---|---|---|---|---|---|
Linear | * | N | Y (scalar only) | Y | Y |
Linear plus bounds | * | Y | N | N | Y |
Scalar nonlinear | N | N | * | Y | Y |
Nonlinear system | N | N | N | * | Y |
Nonlinear system plus bounds | N | N | N | N | * |
Example: 'intlinprog'
Data Types: char
| string
ObjectiveDerivative
— Indication to use automatic differentiation for objective function
'auto'
(default) | 'auto-forward'
| 'auto-reverse'
| 'finite-differences'
Indication to use automatic differentiation (AD) for nonlinear
objective function, specified as 'auto'
(use AD if
possible), 'auto-forward'
(use forward AD if
possible), 'auto-reverse'
(use reverse AD if
possible), or 'finite-differences'
(do not use AD).
Choices including auto
cause the underlying solver to
use gradient information when solving the problem provided that the
objective function is supported, as described in Supported Operations for Optimization Variables and Expressions. For
an example, see Effect of Automatic Differentiation in Problem-Based Optimization.
Solvers choose the following type of AD by default:
-
For a general nonlinear objective function,
fmincon
defaults
to reverse AD for the objective function.fmincon
defaults to
reverse AD for the nonlinear constraint function when the number of nonlinear
constraints is less than the number of variables. Otherwise,
fmincon
defaults to forward AD for the nonlinear constraint
function. -
For a general nonlinear objective function,
fminunc
defaults
to reverse AD. -
For a least-squares objective function,
fmincon
and
fminunc
default to forward AD for the objective function.
For the definition of a problem-based least-squares objective function, see Write Objective Function for Problem-Based Least Squares. -
lsqnonlin
defaults to forward AD when the number of elements
in the objective vector is greater than or equal to the number of variables.
Otherwise,lsqnonlin
defaults to reverse AD. -
fsolve
defaults to forward AD when the number of equations is
greater than or equal to the number of variables. Otherwise,
fsolve
defaults to reverse AD.
Example: 'finite-differences'
Data Types: char
| string
ConstraintDerivative
— Indication to use automatic differentiation for constraint functions
'auto'
(default) | 'auto-forward'
| 'auto-reverse'
| 'finite-differences'
Indication to use automatic differentiation (AD) for nonlinear
constraint functions, specified as 'auto'
(use AD if
possible), 'auto-forward'
(use forward AD if
possible), 'auto-reverse'
(use reverse AD if
possible), or 'finite-differences'
(do not use AD).
Choices including auto
cause the underlying solver to
use gradient information when solving the problem provided that the
constraint functions are supported, as described in Supported Operations for Optimization Variables and Expressions. For
an example, see Effect of Automatic Differentiation in Problem-Based Optimization.
Solvers choose the following type of AD by default:
-
For a general nonlinear objective function,
fmincon
defaults
to reverse AD for the objective function.fmincon
defaults to
reverse AD for the nonlinear constraint function when the number of nonlinear
constraints is less than the number of variables. Otherwise,
fmincon
defaults to forward AD for the nonlinear constraint
function. -
For a general nonlinear objective function,
fminunc
defaults
to reverse AD. -
For a least-squares objective function,
fmincon
and
fminunc
default to forward AD for the objective function.
For the definition of a problem-based least-squares objective function, see Write Objective Function for Problem-Based Least Squares. -
lsqnonlin
defaults to forward AD when the number of elements
in the objective vector is greater than or equal to the number of variables.
Otherwise,lsqnonlin
defaults to reverse AD. -
fsolve
defaults to forward AD when the number of equations is
greater than or equal to the number of variables. Otherwise,
fsolve
defaults to reverse AD.
Example: 'finite-differences'
Data Types: char
| string
EquationDerivative
— Indication to use automatic differentiation for equations
'auto'
(default) | 'auto-forward'
| 'auto-reverse'
| 'finite-differences'
Indication to use automatic differentiation (AD) for nonlinear
constraint functions, specified as 'auto'
(use AD if
possible), 'auto-forward'
(use forward AD if
possible), 'auto-reverse'
(use reverse AD if
possible), or 'finite-differences'
(do not use AD).
Choices including auto
cause the underlying solver to
use gradient information when solving the problem provided that the
equation functions are supported, as described in Supported Operations for Optimization Variables and Expressions. For
an example, see Effect of Automatic Differentiation in Problem-Based Optimization.
Solvers choose the following type of AD by default:
-
For a general nonlinear objective function,
fmincon
defaults
to reverse AD for the objective function.fmincon
defaults to
reverse AD for the nonlinear constraint function when the number of nonlinear
constraints is less than the number of variables. Otherwise,
fmincon
defaults to forward AD for the nonlinear constraint
function. -
For a general nonlinear objective function,
fminunc
defaults
to reverse AD. -
For a least-squares objective function,
fmincon
and
fminunc
default to forward AD for the objective function.
For the definition of a problem-based least-squares objective function, see Write Objective Function for Problem-Based Least Squares. -
lsqnonlin
defaults to forward AD when the number of elements
in the objective vector is greater than or equal to the number of variables.
Otherwise,lsqnonlin
defaults to reverse AD. -
fsolve
defaults to forward AD when the number of equations is
greater than or equal to the number of variables. Otherwise,
fsolve
defaults to reverse AD.
Example: 'finite-differences'
Data Types: char
| string
Output Arguments
collapse all
Solution, returned as a structure or an OptimizationValues
vector. sol
is an
OptimizationValues
vector when the problem is multiobjective. For
single-objective problems, the fields of the returned structure are the names of the
optimization variables in the problem. See optimvar
.
fval
— Objective function value at the solution
real number | real vector | real matrix | structure
Objective function value at the solution, returned as one of the
following:
Problem Type | Returned Value(s) |
---|---|
Optimize scalar objective function f(x) |
Real number f(sol) |
Least squares | Real number, the sum of squares of the residuals at the solution |
Solve equation | If prob.Equations is a single entry:Real vector of function values at the solution, meaning the left side minus the right side of the equations |
If prob.Equations has multiple namedfields: Structure with same names as prob.Equations , where each fieldvalue is the left side minus the right side of the named equations |
|
Multiobjective | Matrix with one row for each objective function component, and one column for each solution point. |
Tip
If you neglect to ask for fval
for an objective
defined as an optimization expression or equation expression, you can
calculate it using
fval = evaluate(prob.Objective,sol)
If the objective is defined as a structure with only one field,
fval = evaluate(prob.Objective.ObjectiveName,sol)
If the objective is a structure with multiple fields, write a
loop.
fnames = fields(prob.Equations); for i = 1:length(fnames) fval.(fnames{i}) = evaluate(prob.Equations.(fnames{i}),sol); end
Reason the solver stopped, returned as an enumeration variable. You can convert
exitflag
to its numeric equivalent using
double(exitflag)
, and to its string equivalent using
string(exitflag)
.
This table describes the exit flags for the intlinprog
solver.
Exit Flag for intlinprog |
Numeric Equivalent | Meaning |
---|---|---|
OptimalWithPoorFeasibility |
3 |
The solution is feasible with respect to the relative |
IntegerFeasible |
2 | intlinprog stopped prematurely, and found aninteger feasible point. |
OptimalSolution |
|
The solver converged to a solution |
SolverLimitExceeded |
|
See Tolerances and Stopping Criteria. |
OutputFcnStop |
-1 |
intlinprog stopped by an output function or plotfunction. |
NoFeasiblePointFound |
|
No feasible point found. |
Unbounded |
|
The problem is unbounded. |
FeasibilityLost |
|
Solver lost feasibility. |
Exitflags 3
and -9
relate
to solutions that have large infeasibilities. These usually arise from linear constraint
matrices that have large condition number, or problems that have large solution components. To
correct these issues, try to scale the coefficient matrices, eliminate redundant linear
constraints, or give tighter bounds on the variables.
This table describes the exit flags for the linprog
solver.
Exit Flag for linprog |
Numeric Equivalent | Meaning |
---|---|---|
OptimalWithPoorFeasibility |
3 |
The solution is feasible with respect to the relative |
OptimalSolution |
1 |
The solver converged to a solution |
SolverLimitExceeded |
0 |
The number of iterations exceeds |
NoFeasiblePointFound |
-2 |
No feasible point found. |
Unbounded |
-3 |
The problem is unbounded. |
FoundNaN |
-4 |
|
PrimalDualInfeasible |
-5 |
Both primal and dual problems are infeasible. |
DirectionTooSmall |
-7 |
The search direction is too small. No further progress can be |
FeasibilityLost |
-9 |
Solver lost feasibility. |
Exitflags 3
and -9
relate
to solutions that have large infeasibilities. These usually arise from linear constraint
matrices that have large condition number, or problems that have large solution components. To
correct these issues, try to scale the coefficient matrices, eliminate redundant linear
constraints, or give tighter bounds on the variables.
This table describes the exit flags for the lsqlin
solver.
Exit Flag for lsqlin |
Numeric Equivalent | Meaning |
---|---|---|
FunctionChangeBelowTolerance |
3 |
Change in the residual is smaller than the specified tolerance |
StepSizeBelowTolerance |
|
Step size smaller than |
OptimalSolution |
1 |
The solver converged to a solution |
SolverLimitExceeded |
0 |
The number of iterations exceeds |
NoFeasiblePointFound |
-2 |
For optimization problems, the problem is infeasible. Or, for For equation problems, no solution |
IllConditioned |
-4 |
Ill-conditioning prevents further optimization. |
NoDescentDirectionFound |
-8 |
The search direction is too small. No further progress can be |
This table describes the exit flags for the quadprog
solver.
Exit Flag for quadprog |
Numeric Equivalent | Meaning |
---|---|---|
LocalMinimumFound |
4 |
Local minimum found; minimum is not unique. |
FunctionChangeBelowTolerance |
3 |
Change in the objective function value is smaller than the |
StepSizeBelowTolerance |
|
Step size smaller than |
OptimalSolution |
1 |
The solver converged to a solution |
SolverLimitExceeded |
0 |
The number of iterations exceeds |
NoFeasiblePointFound |
-2 |
The problem is infeasible. Or, for the |
IllConditioned |
-4 |
Ill-conditioning prevents further optimization. |
Nonconvex |
|
Nonconvex problem detected. |
NoDescentDirectionFound |
-8 |
Unable to compute a step direction. |
This table describes the exit flags for the coneprog
solver.
Exit Flag for coneprog |
Numeric Equivalent | Meaning |
---|---|---|
OptimalSolution |
1 |
The solver converged to a solution |
SolverLimitExceeded |
0 |
The number of iterations exceeds |
NoFeasiblePointFound |
-2 |
The problem is infeasible. |
Unbounded |
-3 |
The problem is unbounded. |
DirectionTooSmall |
|
The search direction became too small. No further progress |
Unstable |
-10 |
The problem is numerically unstable. |
This table describes the exit flags for the lsqcurvefit
or
lsqnonlin
solver.
Exit Flag for lsqnonlin |
Numeric Equivalent | Meaning |
---|---|---|
SearchDirectionTooSmall |
4 |
Magnitude of search direction was smaller than |
FunctionChangeBelowTolerance |
3 |
Change in the residual was less than |
StepSizeBelowTolerance |
|
Step size smaller than |
OptimalSolution |
1 |
The solver converged to a solution |
SolverLimitExceeded |
0 |
Number of iterations exceeded |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
-2 |
For optimization problems, problem is infeasible: the bounds For equation problems, no solution |
This table describes the exit flags for the fminunc
solver.
Exit Flag for fminunc |
Numeric Equivalent | Meaning |
---|---|---|
NoDecreaseAlongSearchDirection |
5 |
Predicted decrease in the objective function is less than the |
FunctionChangeBelowTolerance |
3 |
Change in the objective function value is less than the |
StepSizeBelowTolerance |
|
Change in |
OptimalSolution |
1 |
Magnitude of gradient is smaller than the |
SolverLimitExceeded |
0 |
Number of iterations exceeds |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
Unbounded |
-3 |
Objective function at current iteration is below |
This table describes the exit flags for the fmincon
solver.
Exit Flag for fmincon |
Numeric Equivalent | Meaning |
---|---|---|
NoDecreaseAlongSearchDirection |
5 |
Magnitude of directional derivative in search direction is less |
SearchDirectionTooSmall |
4 |
Magnitude of the search direction is less than |
FunctionChangeBelowTolerance |
3 |
Change in the objective function value is less than |
StepSizeBelowTolerance |
|
Change in |
OptimalSolution |
1 |
First-order optimality measure is less than |
SolverLimitExceeded |
0 |
Number of iterations exceeds |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
-2 |
No feasible point found. |
Unbounded |
-3 |
Objective function at current iteration is below |
This table describes the exit flags for the fsolve
solver.
Exit Flag for fsolve |
Numeric Equivalent | Meaning |
---|---|---|
SearchDirectionTooSmall |
4 |
Magnitude of the search direction is less than |
FunctionChangeBelowTolerance |
3 |
Change in the objective function value is less than |
StepSizeBelowTolerance |
|
Change in |
OptimalSolution |
1 |
First-order optimality measure is less than |
SolverLimitExceeded |
0 |
Number of iterations exceeds |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
-2 |
Converged to a point that is not a root. |
TrustRegionRadiusTooSmall |
-3 |
Equation not solved. Trust region radius became too small |
This table describes the exit flags for the fzero
solver.
Exit Flag for fzero |
Numeric Equivalent | Meaning |
---|---|---|
OptimalSolution |
1 |
Equation solved. |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
FoundNaNInfOrComplex |
-4 |
|
SingularPoint |
-5 |
Might have converged to a singular point. |
CannotDetectSignChange |
-6 |
Did not find two points with opposite signs of function value. |
This table describes the exit flags for the patternsearch
solver.
Exit Flag for patternsearch |
Numeric Equivalent | Meaning |
---|---|---|
SearchDirectionTooSmall |
4 |
The magnitude of the step is smaller than machine precision, |
FunctionChangeBelowTolerance |
3 |
The change in |
StepSizeBelowTolerance |
|
Change in |
SolverConvergedSuccessfully |
1 |
Without nonlinear constraints |
With nonlinear constraints |
||
SolverLimitExceeded |
0 |
The maximum number of function evaluations or iterations is |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
-2 |
No feasible point found. |
In the nonlinear constraint solver, the complementarity measure
is the norm of the vector whose elements are
ciλi, where
ci is the nonlinear inequality
constraint violation, and λi is the
corresponding Lagrange multiplier.
This table describes the exit flags for the ga
solver.
Exit Flag for ga |
Numeric Equivalent | Meaning |
---|---|---|
MinimumFitnessLimitReached |
5 |
Minimum fitness limit |
SearchDirectionTooSmall |
4 |
The magnitude of the step is smaller than machine precision, |
FunctionChangeBelowTolerance |
3 |
Value of the fitness function did not change in |
SolverConvergedSuccessfully |
1 |
Without nonlinear constraints |
With nonlinear constraints |
||
SolverLimitExceeded |
0 |
Maximum number of generations |
OutputFcnStop |
-1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
-2 |
No feasible point found. |
StallTimeLimitExceeded |
-4 |
Stall time limit |
TimeLimitExceeded |
-5 |
Time limit |
This table describes the exit flags for the particleswarm
solver.
Exit Flag for particleswarm |
Numeric Equivalent | Meaning |
---|---|---|
SolverConvergedSuccessfully |
1 |
Relative change in the objective value over the last |
SolverLimitExceeded |
0 |
Number of iterations exceeded |
OutputFcnStop |
-1 |
Iterations stopped by output function or plot |
NoFeasiblePointFound |
-2 |
Bounds are inconsistent: for some |
Unbounded |
-3 |
Best objective function value is below |
StallTimeLimitExceeded |
-4 |
Best objective function value did not change within |
TimeLimitExceeded |
-5 |
Run time exceeded |
This table describes the exit flags for the simulannealbnd
solver.
Exit Flag for simulannealbnd |
Numeric Equivalent | Meaning |
---|---|---|
ObjectiveValueBelowLimit |
5 |
Objective function value is less than |
SolverConvergedSuccessfully |
1 |
Average change in the value of the objective function over |
SolverLimitExceeded |
0 |
Maximum number of generations |
OutputFcnStop |
-1 |
Optimization terminated by an output function or plot |
NoFeasiblePointFound |
-2 |
No feasible point found. |
TimeLimitExceeded |
-5 |
Time limit exceeded. |
This table describes the exit flags for the surrogateopt
solver.
Exit Flag for surrogateopt |
Numeric Equivalent | Meaning |
---|---|---|
BoundsEqual |
10 |
Problem has a unique feasible solution due to one of the
|
FeasiblePointFound |
3 |
Feasible point found. Solver stopped because too few new feasible points were found to continue. |
ObjectiveLimitAttained |
1 |
The objective function value is less than |
SolverLimitExceeded |
0 |
The number of function evaluations exceeds |
OutputFcnStop |
-1 |
The optimization is terminated by an output function or plot |
NoFeasiblePointFound |
-2 |
No feasible point is found due to one of the following:
|
This table describes the exit flags for the MultiStart
and
GlobalSearch
solvers.
Exit Flag for MultiStart orGlobalSearch |
Numeric Equivalent | Meaning |
---|---|---|
LocalMinimumFoundSomeConverged |
2 |
At least one local minimum found. Some runs of the local solver converged. |
LocalMinimumFoundAllConverged |
1 |
At least one local minimum found. All runs of the local solver converged. |
SolverLimitExceeded |
0 |
No local minimum found. Local solver called at least once and at least one local solver call ran out of iterations. |
OutputFcnStop |
–1 |
Stopped by an output function or plot function. |
NoFeasibleLocalMinimumFound |
–2 |
No feasible local minimum found. |
TimeLimitExceeded |
–5 |
MaxTime limit exceeded. |
NoSolutionFound |
–8 |
No solution found. All runs had local solver exit flag –2 or smaller, not all equal –2. |
FailureInSuppliedFcn |
–10 |
Encountered failures in the objective or nonlinear constraint functions. |
This table describes the exit flags for the paretosearch
solver.
Exit Flag for paretosearch |
Numeric Equivalent | Meaning |
---|---|---|
SolverConvergedSuccessfully |
1 |
One of the following conditions is met:
|
SolverLimitExceeded |
0 |
Number of iterations exceedsoptions.MaxIterations , or the number of functionevaluations exceeds options.MaxFunctionEvaluations . |
OutputFcnStop |
–1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
–2 |
Solver cannot find a point satisfying all the constraints. |
TimeLimitExceeded |
–5 |
Optimization time exceeds options.MaxTime . |
This table describes the exit flags for the gamultiobj
solver.
Exit Flag for paretosearch |
Numeric Equivalent | Meaning |
---|---|---|
SolverConvergedSuccessfully |
1 |
Geometric average of the relative change in value of the spread overoptions.MaxStallGenerations generations is lessthan options.FunctionTolerance , and the final spreadis less than the mean spread over the past options.MaxStallGenerations generations. |
SolverLimitExceeded |
0 |
Number of generations exceedsoptions.MaxGenerations . |
OutputFcnStop |
–1 |
Stopped by an output function or plot function. |
NoFeasiblePointFound |
–2 |
Solver cannot find a point satisfying all the constraints. |
TimeLimitExceeded |
–5 |
Optimization time exceeds options.MaxTime . |
output
— Information about optimization process
structure
Information about the optimization process, returned as a structure. The output
structure contains the fields in the relevant underlying solver output field, depending
on which solver solve
called:
-
'fmincon'
output
-
'fminunc'
output
-
'fsolve'
output
-
'fzero'
output
-
'intlinprog'
output
-
'linprog'
output
-
'lsqcurvefit'
or'lsqnonlin'
output
-
'lsqlin'
output
-
'lsqnonneg'
output
-
'quadprog'
output
-
'ga'
output
(Global Optimization Toolbox) -
'gamultiobj'
output
(Global Optimization Toolbox) -
'paretosearch'
output
(Global Optimization Toolbox) -
'particleswarm'
output
(Global Optimization Toolbox) -
'patternsearch'
output
(Global Optimization Toolbox) -
'simulannealbnd'
output
(Global Optimization Toolbox) -
'surrogateopt'
output
(Global Optimization Toolbox)
-
'MultiStart'
and'GlobalSearch'
return
the output structure from the local solver. In addition, the output structure
contains the following fields:-
globalSolver
— Either
'MultiStart'
or
'GlobalSearch'
. -
objectiveDerivative
— Takes the values described at
the end of this section. -
constraintDerivative
— Takes the values described
at the end of this section, or"auto"
when
prob
has no nonlinear constraint. -
solver
— The local solver, such as
'fmincon'
. -
local
— Structure containing extra information
about the optimization.-
sol
— Local solutions, returned as a vector
ofOptimizationValues
objects. -
x0
— Initial points for the local solver,
returned as a cell array. -
exitflag
— Exit flags of local solutions,
returned as an integer vector. -
output
— Structure array, with one row for
each local solution. Each row is the local output structure
corresponding to one local solution.
-
-
solve
includes the additional field Solver
in
the output
structure to identify the solver used, such as
'intlinprog'
.
When Solver
is a nonlinear Optimization Toolbox™ solver, solve
includes one or two extra fields
describing the derivative estimation type. The objectivederivative
and, if appropriate, constraintderivative
fields can take the
following values:
-
"reverse-AD"
for reverse automatic differentiation -
"forward-AD"
for forward automatic differentiation -
"finite-differences"
for finite difference
estimation -
"closed-form"
for linear or quadratic functions
lambda
— Lagrange multipliers at the solution
structure
Lagrange multipliers at the solution, returned as a structure.
Note
solve
does not return lambda
for
equation-solving problems.
For the intlinprog
and fminunc
solvers,
lambda
is empty, []
. For the other solvers,
lambda
has these fields:
-
Variables
– Contains fields for each problem variable. Each problem variable name is a structure with two fields:-
Lower
– Lagrange multipliers associated with the variableLowerBound
property, returned as an array of the same size as the variable. Nonzero entries mean that the solution is at the lower bound. These multipliers are in the structurelambda.Variables.
.variablename
.Lower -
Upper
– Lagrange multipliers associated with the variableUpperBound
property, returned as an array of the same size as the variable. Nonzero entries mean that the solution is at the upper bound. These multipliers are in the structurelambda.Variables.
.variablename
.Upper
-
-
Constraints
– Contains a field for each problem constraint. Each problem constraint is in a structure whose name is the constraint name, and whose value is a numeric array of the same size as the constraint. Nonzero entries mean that the constraint is active at the solution. These multipliers are in the structurelambda.Constraints.
.constraintname
Note
Elements of a constraint array all have the same comparison
(<=
,==
, or
>=
) and are all of the same type (linear, quadratic,
or nonlinear).
Algorithms
collapse all
Conversion to Solver Form
Internally, the solve
function
solves optimization problems by calling a solver. For the default solver for the problem and
supported solvers for the problem, see the solvers
function. You can override the default by using the 'solver'
name-value pair argument when calling
solve
.
Before solve
can call a
solver, the problems must be converted to solver form, either by solve
or
some other associated functions or objects. This conversion entails, for example, linear
constraints having a matrix representation rather than an optimization variable
expression.
The first step in the algorithm occurs as you place
optimization expressions into the problem. An OptimizationProblem
object has an internal list of the variables used in its
expressions. Each variable has a linear index in the expression, and a size. Therefore, the
problem variables have an implied matrix form. The prob2struct
function performs the conversion from problem form to solver form. For an example, see Convert Problem to Structure.
For nonlinear optimization problems, solve
uses automatic
differentiation to compute the gradients of the objective function and
nonlinear constraint functions. These derivatives apply when the objective and constraint
functions are composed of Supported Operations for Optimization Variables and Expressions. When automatic
differentiation does not apply, solvers estimate derivatives using finite differences. For
details of automatic differentiation, see Automatic Differentiation Background. You can control how
solve
uses automatic differentiation with the ObjectiveDerivative
name-value argument.
For the algorithm that
intlinprog
uses to solve MILP problems, see intlinprog Algorithm. For
the algorithms that linprog
uses to solve linear programming problems,
see Linear Programming Algorithms.
For the algorithms that quadprog
uses to solve quadratic programming
problems, see Quadratic Programming Algorithms. For linear or nonlinear least-squares solver
algorithms, see Least-Squares (Model Fitting) Algorithms. For nonlinear solver algorithms, see Unconstrained Nonlinear Optimization Algorithms and
Constrained Nonlinear Optimization Algorithms.
For Global Optimization Toolbox solver algorithms, see Global Optimization Toolbox documentation.
For nonlinear equation solving, solve
internally represents each
equation as the difference between the left and right sides. Then solve
attempts to minimize the sum of squares of the equation components. For the algorithms for
solving nonlinear systems of equations, see Equation Solving Algorithms. When
the problem also has bounds, solve
calls lsqnonlin
to minimize the sum of squares of equation components. See Least-Squares (Model Fitting) Algorithms.
Automatic Differentiation
Automatic differentiation (AD) applies to the solve
and
prob2struct
functions under the following conditions:
-
The objective and constraint functions are supported, as described in Supported Operations for Optimization Variables and Expressions. They do not
require use of thefcn2optimexpr
function. -
The solver called by
solve
isfmincon
,fminunc
,fsolve
, orlsqnonlin
. -
For optimization problems, the
'ObjectiveDerivative'
and
'ConstraintDerivative'
name-value pair arguments for
solve
orprob2struct
are set to
'auto'
(default),'auto-forward'
, or
'auto-reverse'
. -
For equation problems, the
'EquationDerivative'
option is set
to'auto'
(default),'auto-forward'
, or
'auto-reverse'
.
When AD Applies | All Constraint Functions Supported | One or More Constraints Not Supported |
---|---|---|
Objective Function Supported | AD used for objective and constraints | AD used for objective only |
Objective Function Not Supported | AD used for constraints only | AD not used |
When these conditions are not satisfied, solve
estimates gradients by
finite differences, and prob2struct
does not create gradients in its
generated function files.
Solvers choose the following type of AD by default:
-
For a general nonlinear objective function,
fmincon
defaults
to reverse AD for the objective function.fmincon
defaults to
reverse AD for the nonlinear constraint function when the number of nonlinear
constraints is less than the number of variables. Otherwise,
fmincon
defaults to forward AD for the nonlinear constraint
function. -
For a general nonlinear objective function,
fminunc
defaults
to reverse AD. -
For a least-squares objective function,
fmincon
and
fminunc
default to forward AD for the objective function.
For the definition of a problem-based least-squares objective function, see Write Objective Function for Problem-Based Least Squares. -
lsqnonlin
defaults to forward AD when the number of elements
in the objective vector is greater than or equal to the number of variables.
Otherwise,lsqnonlin
defaults to reverse AD. -
fsolve
defaults to forward AD when the number of equations is
greater than or equal to the number of variables. Otherwise,
fsolve
defaults to reverse AD.
Note
To use automatic derivatives in a problem converted by prob2struct
, pass options specifying these derivatives.
options = optimoptions('fmincon','SpecifyObjectiveGradient',true,... 'SpecifyConstraintGradient',true); problem.options = options;
Currently, AD works only for first derivatives; it does not apply to second or higher
derivatives. So, for example, if you want to use an analytic Hessian to speed your
optimization, you cannot use solve
directly, and must instead use the
approach described in Supply Derivatives in Problem-Based Workflow.
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
solve
estimates derivatives in parallel for nonlinear solvers
when the UseParallel
option for the solver is
true
. For example,
options = optimoptions('fminunc','UseParallel',true); [sol,fval] = solve(prob,x0,'Options',options)
solve
does not use parallel derivative estimation when all
objective and nonlinear constraint functions consist only of supported operations,
as described in Supported Operations for Optimization Variables and Expressions. In this case,
solve
uses automatic differentiation for calculating
derivatives. See Automatic Differentiation.
You can override automatic differentiation and use finite difference estimates in
parallel by setting the 'ObjectiveDerivative'
and 'ConstraintDerivative'
arguments to
'finite-differences'
.
When you specify a Global Optimization Toolbox solver that support parallel computation (ga
(Global Optimization Toolbox), particleswarm
(Global Optimization Toolbox), patternsearch
(Global Optimization Toolbox), and surrogateopt
(Global Optimization Toolbox)), solve
compute in parallel when
the UseParallel
option for the solver is true
.
For example,
options = optimoptions("patternsearch","UseParallel",true); [sol,fval] = solve(prob,x0,"Options",options,"Solver","patternsearch")
Version History
Introduced in R2017b
expand all
R2018b: solve(prob,solver)
, solve(prob,options)
, and solve(prob,solver,options)
syntaxes have been removed
To choose options or the underlying solver for solve
, use
name-value pairs. For example,
sol = solve(prob,'options',opts,'solver','quadprog');
The previous syntaxes were not as flexible, standard, or extensible as name-value
pairs.
Тема
5.2. Технология решения нелинейных
уравнений средствами MatLab
Для
решения систем алгебраических уравнений
и одиночных уравнений служит функция
solve:
-
solve(expr1,
expr2,…
exprN,
var1,
var2,…
varN)–
возвращает значения переменных
var1,
при которых соблюдаются равенства,
заданные выражениями
exprI.
Если в выражениях не используются знаки
равенства, то
полагается ехргI
= 0; -
solve(expr1,
expr2,
….. exprN)–аналогична
предшествующей функции,
но переменные, по которым ищется решение,
определяются функцией
findsym.
Пример
4.2-1. Решить
несколько нелинейных уравнений.
Пример4.2-1 |
» » ans [ 1] [ [ » » ans [ [ »S S
x
y » ans [4] [1] [1] » ans [-1] [2] [2] » ans 0.52359877559829887307710723054658 >> |
Пример4.2-2.
Отделить корни уравнения
с
непрерывной правой частью.
Найдем отрезок, на концах которого
имеет
разные знаки. Т.е. решим уравнение
.
Пример |
syms >> >> >> >> |
В математическом пакете
MatLab
имеется также ряд встроенных функций
для численного вычисления корней
уравнений.
Рассмотрим программные
средства MatLabна
примерах.
Пример
4.2-3. Локализовать
корни уравнения f(x)=x3–cos(x)+1.
Пример |
>>f >>x |
>>figure(‘Name’, >>plot(x, >>figure(‘Name’, >>figure(‘Name’, >> |
Решение
алгебраических и трансцендентных
уравнений в среде MatLAB
проще реализовать с помощью встроенных
функций: solve(),
fzero(),
roors().
Для
нахождения вещественных корней уравнений
вида f(х)=0
используется функция fzero().
Алгоритм,
реализованный этой функцией, представляет
собой комбинацию
метода дихотомии (деления пополам),
метода секущих и метода обратной
квадратичной интерполяции.
В простейшем варианте обращения кроме
указателя
на функцию, корень которой ищется,
задается окрестность х0,
с которой
начинается поиск: х
= fzero(f,
x0).
Аргумент
fможет
быть задан одним из способов:
-
формойс
неизвестным х,
заключенная в апострофы; -
именем
m-файла
(в апострофах и без расширения m); -
указателем
на функцию (например, @f_name); -
указателем
на анонимную функцию (например, f_handie).
При этом формула, заключенная
в апострофы, в качестве независимой
переменной может
содержать только х.
Использование независимой переменной
с другим именем
вызовет сообщение об ошибке.
Аргумент
х0
может быть задан одним из двух способов:
-
вектором
[a;b],
представляющим интервал (а<b),на
концах которого функция
f()меняет
знак, что гарантирует нахождение, по
крайней мере, одного
корня на этом интервале; -
скалярным
значением, в окрестности которого
предполагается нахождение
корня. В этом случае функция fzero()
сама пытается найти отрезок
с центром в заданной точке х0,
на концах которого функцияf
()меняет
знак.
Чтобы
облегчить работу по выбору начального
приближения, разумнее всего построить
график функции y=f
(x).
Пример
4.2-4.
Построить график функции f(x)=x∙e–x+sin(x)
для локализации корня.
Пример |
x y plot(x, grid title(‘y=x*exp(-x)+sin(x) |
Из
графика видно, что один из корней
находится на интервале [3;4].
Используем
полученную информациюи
обратимся к функции
fzero(
):
Пример |
>> x= 3.2665 >> |
Вместо
явного задания формулы для функции f
мы могли бы объявить соответствующую
функцию, запомнив ее в виде автономного
m-файла
или включив
ее в качестве подфункции в файл нашей
программы.
Пример |
function x=fzero(@f1, function
y= |
Если
мы хотим получить не только значение
корня, но и узнать значение функции в
найденной точке, то к функции fzero( ) можно
обратиться с двумя выходными параметрами.
В ряде
задач такая точность может оказаться
излишней. MatLab предоставляет пользователю
возможность формировать различные
условия прекращения итерационного
процесса – по точности вычисления
координаты х, по модулю значения функции
f(), по количеству обращений к функции
f() и т. д.
Пример
4.2-5.
Найти
решения tg(x)=0
на
интервале[1;2].
Пример |
>> х 1.5708 f -1.2093e+015 >> |
Якобы
«корень», соответствующий приближенному
значению ?/2,
на самом деле является точкой разрыва,
при переходе через которую функция
меняет знак. Выведенное значение функции
в найденной точке убеждает нас в том,
что найден не корень.
Функция
fzero() может возвратить еще два выходных
параметра.
Пример |
>> >> |
Положительное
значение e_fiag
(обычно, это 1) означает, что удалось
найти
интервал, на концах которого функция
f(
)
меняет знак (пример с tg(x)не
должен притупить вашу бдительность).
Если такой интервал не обнаружен,
то e_fiag=-1.
Структура inform
содержит три поля с именами iterations,
funcCountи
algorithm.
В первом из них находится количество
итераций,
выполненных при поиске корня, во втором
–
количество обращений к функции f(
),
в третьем –
наименование алгоритма, использованного
для нахождения корня.
Пример
4.2-6.
Найти
корень уравнения с помощью функции
fzero().
Пример |
» x f= e_flag inform iterations: funcCount:
algorithm: >> |
В данном случае достижение
высокой точности потребовалось
8 итераций. Простое деление отрезка
пополам для достижения
такой же точности потребовало бы больше
итераций.
Отделение отрезка, на концах
которого функция принимает значения
разных знаков, является принципиальным
для алгоритма, использованного
в функции fzero().
Даже в таких тривиальных уравнениях,
как х2=0,
обычно
не удается найти решение.
Для символьного (аналитического)
решения уравнений в MatLab используется
функция solve(),которая
представляется в следующем
виде:solve(‘f(x)’,x),solve(‘f(x)’),где:
‘f(x)’–
решаемое уравнение, записанное в
одиночных кавычках и представленное в
произвольной форме; x–
искомая символьная неизвестная (symsx).
Рассмотрим технологию
определения корня с помощью функции
solve()
на примерах.
Пример
4.2-7.Найти
решение уравнения2x–3(a–b)=0
в символьном
виде.
Пример |
>>syms >> y log((3*a-3*b)/log(2)) >> |
Пример
4.2-8.Решить
уравнение 2x–4∙x+3=0
аналитически.
|
>>syms >> y 1.418 3.413 >> |
Функция
в ряде случаев позволяет определить
все корни уравнения f(x)=0
без указания начальных
значений x
или областей изоляции корней.
Функция solve()
имеет следующий недостаток. Она не
требует информации о начальном значении
корня или области его изоляции. Поэтому
в случае трансцендентных уравнений и
в ряде других случаев, она не находит
всех корней уравнения.
Пример
4.2-9.Решить
уравнение 2x–3(a–b)=0,
где a
– независимая
переменная.
|
>>syms >> y 1/3*2^x+ >> |
[Введите текст] Страница
11
Соседние файлы в папке Учебное пособие
- #
- #
- #
- #
- #
- #
- #
- #