Как найти решение уравнения в матлабе

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 ==
1','x')
with 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])

Figure contains an axes object. The axes object contains 2 objects of type functionline.

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

eqnEquation 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
.

varVariable 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.

eqnsSystem 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.

varsVariables 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.

RealFlag 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.

ReturnConditionsFlag 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 parameters
with 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 fields
parameters and conditions. For
multiple output variables, solve assigns the parameters
and 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 ==
3,'ReturnConditions',true)
returns the parameters in
params and conditions in
conditions.

IgnoreAnalyticConstraintsSimplification 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 to
true can give you simpler solutions, which could lead to
results 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 be
solved otherwise. For details, see Algorithms.

See Shorten Result with Simplification Rules.

IgnorePropertiesFlag 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.

MaxDegreeMaximum 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.

PrincipalValueFlag 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',
true)
returns the parameter 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',
true)
returns the condition in(k, 'integer') in
conditions. The solution in solx is valid only
under this condition.

Tips

  • If solve cannot find a solution and
    ReturnConditions is false, 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 is true,
    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 is false, 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 by solve.

  • 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 use syms to initialize the parameter. For
    example, if the parameter is k, use syms k.

  • The variable names parameters and conditions are
    not allowed as inputs to solve.

  • 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
    which solve 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 to b and vice versa.

    To ensure the order of the returned solutions, specify the variables
    vars. For example, the call [b,a] =
    solve(eqns,b,a)
    assigns the solutions for a to
    a and the solutions for b 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,
x)
solves 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,
'integer')
on the solution, which means 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')

Figure contains an axes object. The axes object with title Both sides of equation cos(x) = -sin(x) contains 2 objects of type functionline. These objects represent cos(x), -sin(x).

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)

Figure contains an axes object. The axes object with title Both sides of equation cos(x) = -sin(x) contains 3 objects of type functionline, scatter. These objects represent cos(x), -sin(x).

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])

Figure contains an axes object. The axes object contains 2 objects of type functionline.

Найдите другое решение путем прямого вызова числового решателя 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. К ним нужно получить доступ с помощью выходного аргумента, который содержит их. В качестве альтернативы использовать параметры в использовании рабочего пространства MATLAB syms инициализировать параметр. Например, если параметром является 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.

Figure Optimization Plot Function contains an axes object. The axes object with title Best Function Value: -6.55113, xlabel Iteration, ylabel Function value contains a line object which displays its values using only markers. This object represents Best function value.

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

probOptimization 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;

x0Initial 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) and particleswarm (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

msMultiple 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)

MinNumStartPointsMinimum 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

OptionsOptimization 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')

SolverOptimization 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)

fminunc for problems with no constraints, otherwise fmincon

Mixed-Integer Nonlinear Programming (MINLP) ga (Global Optimization Toolbox)
Multiobjective gamultiobj (Global Optimization Toolbox)

In this table, Yes 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

ObjectiveDerivativeIndication 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

ConstraintDerivativeIndication 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

EquationDerivativeIndication 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 named
fields: Structure with same names as
prob.Equations, where each field
value 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
ConstraintTolerance tolerance, but is not
feasible with respect to the absolute tolerance.

IntegerFeasible 2 intlinprog stopped prematurely, and found an
integer feasible point.
OptimalSolution

1

The solver converged to a solution
x.

SolverLimitExceeded

0

intlinprog exceeds one of the following
tolerances:

  • LPMaxIterations

  • MaxNodes

  • MaxTime

  • RootLPMaxIterations

See Tolerances and Stopping Criteria. solve also
returns this exit flag when it runs out of memory at the root
node.

OutputFcnStop -1 intlinprog stopped by an output function or plot
function.
NoFeasiblePointFound

-2

No feasible point found.

Unbounded

-3

The problem is unbounded.

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 linprog solver.

Exit Flag for linprog Numeric Equivalent Meaning
OptimalWithPoorFeasibility 3

The solution is feasible with respect to the relative
ConstraintTolerance tolerance, but is not
feasible with respect to the absolute tolerance.

OptimalSolution 1

The solver converged to a solution
x.

SolverLimitExceeded 0

The number of iterations exceeds
options.MaxIterations.

NoFeasiblePointFound -2

No feasible point found.

Unbounded -3

The problem is unbounded.

FoundNaN -4

NaN value encountered during execution of
the algorithm.

PrimalDualInfeasible -5

Both primal and dual problems are infeasible.

DirectionTooSmall -7

The search direction is too small. No further progress can be
made.

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
options.FunctionTolerance.
(trust-region-reflective
algorithm)

StepSizeBelowTolerance

2

Step size smaller than
options.StepTolerance, constraints satisfied.
(interior-point algorithm)

OptimalSolution 1

The solver converged to a solution
x.

SolverLimitExceeded 0

The number of iterations exceeds
options.MaxIterations.

NoFeasiblePointFound -2

For optimization problems, the problem is infeasible. Or, for
the interior-point algorithm, step size smaller
than options.StepTolerance, but constraints are
not satisfied.

For equation problems, no solution
found.

IllConditioned -4

Ill-conditioning prevents further optimization.

NoDescentDirectionFound -8

The search direction is too small. No further progress can be
made. (interior-point algorithm)

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
specified tolerance options.FunctionTolerance.
(trust-region-reflective
algorithm)

StepSizeBelowTolerance

2

Step size smaller than
options.StepTolerance, constraints satisfied.
(interior-point-convex
algorithm)

OptimalSolution 1

The solver converged to a solution
x.

SolverLimitExceeded 0

The number of iterations exceeds
options.MaxIterations.

NoFeasiblePointFound -2

The problem is infeasible. Or, for the
interior-point algorithm, step size smaller
than options.StepTolerance, but constraints are
not satisfied.

IllConditioned -4

Ill-conditioning prevents further optimization.

Nonconvex

-6

Nonconvex problem detected.
(interior-point-convex
algorithm)

NoDescentDirectionFound -8

Unable to compute a step direction.
(interior-point-convex
algorithm)

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
x.

SolverLimitExceeded 0

The number of iterations exceeds
options.MaxIterations, or the solution time
in seconds exceeded
options.MaxTime.

NoFeasiblePointFound -2

The problem is infeasible.

Unbounded -3

The problem is unbounded.

DirectionTooSmall

-7

The search direction became too small. No further progress
could be made.

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
options.StepTolerance.

FunctionChangeBelowTolerance 3

Change in the residual was less than
options.FunctionTolerance.

StepSizeBelowTolerance

2

Step size smaller than
options.StepTolerance.

OptimalSolution 1

The solver converged to a solution
x.

SolverLimitExceeded 0

Number of iterations exceeded
options.MaxIterations or number of function
evaluations exceeded
options.MaxFunctionEvaluations.

OutputFcnStop -1

Stopped by an output function or plot function.

NoFeasiblePointFound -2

For optimization problems, problem is infeasible: the bounds
lb and ub are
inconsistent.

For equation problems, no solution
found.

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
options.FunctionTolerance
tolerance.

FunctionChangeBelowTolerance 3

Change in the objective function value is less than the
options.FunctionTolerance
tolerance.

StepSizeBelowTolerance

2

Change in x is smaller than the
options.StepTolerance
tolerance.

OptimalSolution 1

Magnitude of gradient is smaller than the
options.OptimalityTolerance
tolerance.

SolverLimitExceeded 0

Number of iterations exceeds
options.MaxIterations or number of function
evaluations exceeds
options.MaxFunctionEvaluations.

OutputFcnStop -1

Stopped by an output function or plot function.

Unbounded -3

Objective function at current iteration is below
options.ObjectiveLimit.

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
than 2*options.OptimalityTolerance and maximum
constraint violation is less than
options.ConstraintTolerance.

SearchDirectionTooSmall 4

Magnitude of the search direction is less than
2*options.StepTolerance and maximum
constraint violation is less than
options.ConstraintTolerance.

FunctionChangeBelowTolerance 3

Change in the objective function value is less than
options.FunctionTolerance and maximum
constraint violation is less than
options.ConstraintTolerance.

StepSizeBelowTolerance

2

Change in x is less than
options.StepTolerance and maximum constraint
violation is less than
options.ConstraintTolerance.

OptimalSolution 1

First-order optimality measure is less than
options.OptimalityTolerance, and maximum
constraint violation is less than
options.ConstraintTolerance.

SolverLimitExceeded 0

Number of iterations exceeds
options.MaxIterations or number of function
evaluations exceeds
options.MaxFunctionEvaluations.

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
options.ObjectiveLimit and maximum constraint
violation is less than
options.ConstraintTolerance.

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
options.StepTolerance, equation
solved.

FunctionChangeBelowTolerance 3

Change in the objective function value is less than
options.FunctionTolerance, equation
solved.

StepSizeBelowTolerance

2

Change in x is less than
options.StepTolerance, equation
solved.

OptimalSolution 1

First-order optimality measure is less than
options.OptimalityTolerance, equation
solved.

SolverLimitExceeded 0

Number of iterations exceeds
options.MaxIterations or number of function
evaluations exceeds
options.MaxFunctionEvaluations.

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
(trust-region-dogleg
algorithm).

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

NaN, Inf, or complex
value encountered during search for an interval containing a sign
change.

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,
and the constraint violation is less than
ConstraintTolerance.

FunctionChangeBelowTolerance 3

The change in fval and the mesh size are
both less than the specified tolerance, and the constraint violation
is less than ConstraintTolerance.

StepSizeBelowTolerance

2

Change in x and the mesh size are both
smaller than StepTolerance, and the constraint
violation is less than
ConstraintTolerance.

SolverConvergedSuccessfully 1

Without nonlinear constraints
— The magnitude of the mesh size is less than the specified
tolerance, and the constraint violation is less than
ConstraintTolerance.

With nonlinear constraints
— The magnitude of the complementarity
measure
(defined after this table) is less than
sqrt(ConstraintTolerance), the subproblem is
solved using a mesh finer than MeshTolerance, and
the constraint violation is less than
ConstraintTolerance.

SolverLimitExceeded 0

The maximum number of function evaluations or iterations is
reached.

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 FitnessLimit reached
and the constraint violation is less than
ConstraintTolerance.

SearchDirectionTooSmall 4

The magnitude of the step is smaller than machine precision,
and the constraint violation is less than
ConstraintTolerance.

FunctionChangeBelowTolerance 3

Value of the fitness function did not change in
MaxStallGenerations generations and the
constraint violation is less than
ConstraintTolerance.

SolverConvergedSuccessfully 1

Without nonlinear constraints
— Average cumulative change in value of the fitness function
over MaxStallGenerations generations is less than
FunctionTolerance, and the constraint
violation is less than
ConstraintTolerance.

With nonlinear constraints
— Magnitude of the complementarity measure (see Complementarity Measure (Global Optimization Toolbox)) is
less than sqrt(ConstraintTolerance), the
subproblem is solved using a tolerance less than
FunctionTolerance, and the constraint
violation is less than
ConstraintTolerance.

SolverLimitExceeded 0

Maximum number of generations MaxGenerations
exceeded.

OutputFcnStop -1

Stopped by an output function or plot function.

NoFeasiblePointFound -2

No feasible point found.

StallTimeLimitExceeded -4

Stall time limit MaxStallTime
exceeded.

TimeLimitExceeded -5

Time limit MaxTime exceeded.

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
options.MaxStallIterations iterations is less
than options.FunctionTolerance.

SolverLimitExceeded 0

Number of iterations exceeded
options.MaxIterations.

OutputFcnStop -1

Iterations stopped by output function or plot
function.

NoFeasiblePointFound -2

Bounds are inconsistent: for some i,
lb(i) > ub(i).

Unbounded -3

Best objective function value is below
options.ObjectiveLimit.

StallTimeLimitExceeded -4

Best objective function value did not change within
options.MaxStallTime seconds.

TimeLimitExceeded -5

Run time exceeded options.MaxTime
seconds.

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
options.ObjectiveLimit.

SolverConvergedSuccessfully 1

Average change in the value of the objective function over
options.MaxStallIterations iterations is less
than options.FunctionTolerance.

SolverLimitExceeded 0

Maximum number of generations MaxGenerations
exceeded.

OutputFcnStop -1

Optimization terminated by an output function or plot
function.

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
following:

  • All upper bounds ub (Global Optimization Toolbox) are equal to the lower bounds lb (Global Optimization Toolbox).

  • The linear equality constraints Aeq*x =
    beq
    and the bounds have a unique solution
    point.

surrogateopt returns the
feasible point and function value without performing any
optimization.

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
options.ObjectiveLimit. This exit flag takes
precedence over exit flag 10 when both
apply.

SolverLimitExceeded 0

The number of function evaluations exceeds
options.MaxFunctionEvaluations or the elapsed
time exceeds options.MaxTime. If the problem has
nonlinear inequalities, the solution is feasible.

OutputFcnStop -1

The optimization is terminated by an output function or plot
function.

NoFeasiblePointFound -2

No feasible point is found due to one of the following:

  • A lower bound lb(i) exceeds a
    corresponding upper bound ub(i). Or one
    or more ceil(lb(i)) exceeds a
    corresponding floor(ub(i)) for i in
    intcon (Global Optimization Toolbox). In this case,
    solve returns x =
    []
    and fval = [].

  • lb = ub and the point
    lb is infeasible. In this case,
    x = lb, and fval =
    objconstr(x).Fval
    .

  • The linear and, if present, integer constraints are
    infeasible together with the bounds. In this case,
    solve returns x =
    []
    and fval = [].

  • The bounds, integer, and linear constraints are feasible,
    but no feasible solution is found with nonlinear
    constraints. In this case, x is the point
    of least maximum infeasibility of nonlinear constraints, and
    fval = objconstr(x).Fval.

This table describes the exit flags for the MultiStart and
GlobalSearch solvers.

Exit Flag for MultiStart or
GlobalSearch
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:

  • Mesh size of all incumbents is less than
    options.MeshTolerance and constraints
    (if any) are satisfied to within
    options.ConstraintTolerance.

  • Relative change in the spread of the Pareto set is less
    than options.ParetoSetChangeTolerance and
    constraints (if any) are satisfied to within
    options.ConstraintTolerance.

  • Relative change in the volume of the Pareto set is less
    than options.ParetoSetChangeTolerance and
    constraints (if any) are satisfied to within
    options.ConstraintTolerance.

SolverLimitExceeded 0 Number of iterations exceeds
options.MaxIterations, or the number of function
evaluations 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 over
options.MaxStallGenerations generations is less
than options.FunctionTolerance, and the final spread
is less than the mean spread over the past
options.MaxStallGenerations generations.
SolverLimitExceeded 0 Number of generations exceeds
options.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
        of OptimizationValues 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 variable LowerBound 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 structure lambda.Variables.variablename.Lower.

    • Upper – Lagrange multipliers associated with the variable UpperBound 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 structure lambda.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 structure lambda.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 the fcn2optimexpr function.

  • The solver called by solve is fmincon, fminunc, fsolve, or lsqnonlin.

  • For optimization problems, the 'ObjectiveDerivative' and
    'ConstraintDerivative' name-value pair arguments for
    solve or prob2struct 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

»
syms x у;

»
so1ve(x^3 -1, x)

ans
=

[ 1]

[
-1/2+1/2*i*3^(1/2)]

[
-1/2-1/2*i*3^(1/2)]

»
syms a b с

»
solve(a*x^2+b*x+c)

ans
=

[
1/2/a*(-b+(b^2-4*a*c)^(1/2))]

[
1/2/a*(-b-(b^2-4*a*c)^(1/2))]

»S
= solve(
x+y=3,
x*y^2=4,
x, y)

S
=

x
: [3×1 sym]

y
: [3×1 sym]

»
S.x

ans
=

[4]

[1]

[1]

»
S.y

ans
=

[-1]

[2]

[2]

»
solve(
sin(x)=0.5,
x)

ans
=

0.52359877559829887307710723054658

>>

Пример4.2-2
Отделить корни уравнения 
с
непрерывной правой частью. 

Найдем отрезок, на концах которого
имеет
разные знаки. Т.е. решим уравнение  
.

Пример
4.2-2. 

syms
x

>>
f=sym(‘2^x-4*x’);

>>
ezplot(f,-6,6)

>>
grid on

>>

В математическом пакете
MatLab
имеется также ряд встроенных функций
для численного вычисления корней
уравнений.

Рассмотрим программные
средства MatLabна
примерах.

Пример
4.2-3.
Локализовать
корни уравнения
f(x)=x3cos(x)+1.

Пример
3.4-20

>>f
= inline(‘x.^3 – cos(x) + 1’);

>>x
= linspace(-10,10,100);
>>figure(‘Name’,
‘[-10,10]’);
>>axes(‘NextPlot’, ‘Add’);
>>grid
on
>>plot(x, f(x));

>>figure(‘Name’,
‘[-1,1]’);
>>axes(‘NextPlot’, ‘Add’);
>>grid
on
>>x = linspace(-1,1,100);

>>plot(x,
f(x));

>>figure(‘Name’,
‘[-0.6,-0.4]’);
>>axes(‘NextPlot’, ‘Add’);
>>grid
on
>>x = linspace(-0.6,-0.4,100);
>>plot(x,
f(x));

>>figure(‘Name’,
‘[-0.2,0.2]’);
>>axes(‘NextPlot’, ‘Add’);
>>grid
on
>>x = linspace(-0.2,0.2,100);
>>plot(x,
f(x));

>>

Решение
алгебраических и трансцендентных
уравнений в среде 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)=xex+sin(x)
для локализации корня.

Пример
4.2-4.

x
= 0 : 0.1 : 2* pi;

y
= x.*exp(-x)+sin(x);

plot(x,
y)

grid
on

title(‘y=x*exp(-x)+sin(x)
‘)

Из
графика видно, что один из корней
находится на интервале [3;4].
Используем
полученную информациюи
обратимся к функ­ции
fzero(
):

Пример
4.2-4

>>
x=fzero(‘x.*exp(-x)+sin(x)’,[3,4])

x=

3.2665

>>

Вместо
явного задания формулы для функции f
мы могли бы объявить соответствующую
функцию, запомнив ее в виде автономного
m-файла
или включив
ее в качестве подфункции в файл нашей
программы.

Пример
4.2-4

function
fzerol

x=fzero(@f1,
[3;4])

function
y=f1(z)

y=
z*exp(-z)+sin(z);

Если
мы хотим получить не только значение
корня, но и узнать значение функции в
найденной точке, то к функции fzero( ) можно
обратиться с двумя выходными параметрами.

В ряде
задач такая точность может оказаться
излишней. MatLab предо­ставляет пользователю
возможность формировать различные
условия прекращения итерационного
процесса – по точности вычисления
координаты х, по модулю значения функции
f(), по количеству обращений к функции
f() и т. д.

Пример
4.2-5.
Найти
решения
tg(x)=0
на
интервале
[1;2].

Пример
4.2-5

>>
[x,f]=fzero(‘tan(x) ‘, [1,2])

х
=

1.5708

f
=

-1.2093e+015

>>

Якобы
«корень», соответствующий приближенному
значению ?/2,
на самом деле является точкой разрыва,
при переходе через которую функция
меняет знак. Выведенное значение функции
в найденной точке убеждает нас в том,
что найден не корень.

Функция
fzero() может возвратить еще два выходных
параметра.

Пример
4.2-5

>>
[x,f,e_flag,inform] = fzero{f,x0)

>>

Положительное
значение e_fiag
(обычно, это 1) означает, что удалось
най­ти
интервал, на концах которого функция
f(
)
меняет знак (пример с tg(x)не
должен притупить вашу бдительность).
Если такой интервал не обнару­жен,
то e_fiag=-1.
Структура inform
содержит три поля с именами iterations,
funcCountи
algorithm.
В первом из них находится количество
итераций,
выполненных при поиске корня, во втором

количество обращений к функции f(
),
в третьем –
наименование алгоритма, использован­ного
для нахождения корня.

Пример
4.2-6.
Найти
корень уравнения с помощью функции
fzero().

Пример
4.2-6

»
[x,f,e_flag,inform]=fzero(‘x.*exp(-)+sin(x)’,[3,4])

x
= 3.2665

f=
2.0817e-016

e_flag
=

inform
=

iterations:
8

funcCount:
8

algorithm:
‘bisection, interpolation’

>>

В данном случае достижение
высокой точности по­требовалось
8 итераций. Простое деление отрезка
пополам для дости­жения
такой же точности потребовало бы больше
итераций.

Отделение отрезка, на концах
которого функция принимает значения
разных знаков, является принципиальным
для алгоритма, исполь­зованного
в функции fzero().
Даже в таких тривиальных уравнениях,
как х2=0,
обычно
не удается найти решение.

Для символьного (аналитического)
решения уравнений в MatLab используется
функция solve(),которая
представляется в следующем
виде:solve(‘f(x)’,x),solve(‘f(x)’),где:
‘f(x)’–
решаемое уравнение, записанное в
одиночных кавычках и представленное в
произвольной форме; x–
искомая символьная неизвестная (symsx).

Рассмотрим технологию
определения корня с помощью функции
solve()
на примерах.

Пример
4.2-7.
Найти
решение уравнения
2x3(ab)=0
в символьном
виде.

Пример
4.2-7

>>syms
x

>>
y=solve(‘2^x-3*(a-b)=0’)

y
=

log((3*a-3*b)/log(2))

>>

Пример
4.2-8.Решить
уравнение
2x4∙x+3=0
аналитически.


Пример
4.2-8

>>syms
x

>>
y=solve(‘2^x-4*x+3=0’)

y
=

1.418

3.413

>>

Функция
в ряде случаев позволяет определить
все корни уравнения f(x)=0
без указания начальных
значений x
или областей изоляции корней.

Функция solve()
имеет следующий недостаток. Она не
требует информации о начальном значении
корня или области его изоляции. Поэтому
в случае трансцендентных уравнений и
в ряде других случаев, она не находит
всех корней уравнения.

Пример
4.2-9.Решить
уравнение
2x3(ab)=0,
где
a
независимая
переменная.


Пример
4.2-9

>>syms
a

>>
y=solve(‘2^x-3*(a-b)=0’, a)

y
=

1/3*2^x+

>>

[Введите текст] Страница
11

Соседние файлы в папке Учебное пособие

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

Добавить комментарий