Main Content

本页对应的英文页面已更新,但尚未翻译。 若要查看最新内容,请点击此处访问英文页面。


Optimization constraints


An OptimizationConstraint object contains constraints in terms of OptimizationVariable objects or OptimizationExpression objects. Each constraint uses one of these comparison operators: ==, <=, or >=.

A single statement can represent an array of constraints. For example, you can express the constraints that each row of a matrix variable x sums to one, as shown in Create Simple Constraints in Loop.


Create an empty constraint object using optimconstr. Typically, you use a loop to fill the expressions in the object.

If you create an optimization expressions from optimization variables using a comparison operators ==, <=, or >=, then the resulting object is either an OptimizationEquality or an OptimizationInequality. See Compatibility Considerations.

Include constraints in the Constraints property of an optimization problem by using dot notation.

prob = optimproblem;
x = optimvar('x',5,3);
rowsum = sum(x,2);
prob.Constraints.rowsum = rowsum;



Index names, specified as a cell array of strings or character vectors. For information on using index names, see Named Index for Optimization Variables.

数据类型: cell


Optimization variables in the object, specified as a structure of OptimizationVariable objects.

数据类型: struct


infeasibilityConstraint violation at a point
showDisplay information about optimization object
writeSave optimization object description



Create a 5-by-3 optimization variable x.

x = optimvar('x',5,3);

Create the constraint that each row sums to one by using a loop. Initialize the loop using optimconstr.

rowsum = optimconstr(5);
for i = 1:5
    rowsum(i) = sum(x(i,:)) == 1;

Inspect the rowsum object.

rowsum = 
  5x1 Linear OptimizationConstraint array with properties:

    IndexNames: {{}  {}}
     Variables: [1x1 struct] containing 1 OptimizationVariable

  See constraint formulation with show.

Show the constraints in rowsum.

(1, 1)

  x(1, 1) + x(1, 2) + x(1, 3) == 1

(2, 1)

  x(2, 1) + x(2, 2) + x(2, 3) == 1

(3, 1)

  x(3, 1) + x(3, 2) + x(3, 3) == 1

(4, 1)

  x(4, 1) + x(4, 2) + x(4, 3) == 1

(5, 1)

  x(5, 1) + x(5, 2) + x(5, 3) == 1

Compatibility Considerations


R2019b 中的行为有变化

在 R2017b 中推出