www.gusucode.com > mbcdata 工具箱 matlab 源码程序 > mbcdata/@cgoptim/addConstraint.m

    function [optim, label, optimcon] = addConstraint(optim, label, optimcon)
%ADDCONSTRAINT Add a constraint to the optimization
%
%   OPTIM = ADDCONSTRAINT(OPTIM) adds a default new constraint.
%
%   OPTIM = ADDCONSTRAINT(OPTIM, LABEL) adds a default new constraint with
%   the specified label. If LABEL is empty, a default label will be
%   generated for this constraint.
%
%   OPTIM = ADDCONSTRAINT(OPTIM, LABEL, CONSTRAINT) adds a new constraint
%   using the specified constraint object. 
%
%   [OPTIM, LABEL] = ADDCONSTRAINT(OPTIM, ...) additionally returns the
%   label of the new constraint.
%
%   [OPTIM, LABEL, CONSTRAINT] = ADDCONSTRAINT(OPTIM, ...) additionally
%   returns the new constraint object.
%
%   See also CGOPTIM/GETCONSTRAINT, CGOPTIM/SETCONSTRAINT

%  Copyright 2000-2009 The MathWorks, Inc. and Ford Global Technologies, Inc.


if ~canAddConstraint(optim.OptimSetup)
    error(message('mbc:cgoptim:InvalidState'));
end

% Get a unique label for the constraint
if nargin < 2 || isempty(label)
    label = 'Constraint';
    label = generateLabel(optim.OptimSetup, label);
elseif ~ischar(label)
    error(message('mbc:cgoptim:InvalidArgument'));
else
    label = generateLabel(optim.OptimSetup, label, 'allowroot');
end

% Add a new model constraint to the setup
optim.OptimSetup = addModelConstraint(optim.OptimSetup, label, ...
    'lessthan', 0);

% Add the new constraint object
if nargin < 3
    % Create a new default model constraint
    pConExpr = xregpointer(cgexprconstraint(label, xregpointer, 'le', 0));
    optimcon = cgpointconstraint(label, pConExpr);
elseif ~isa(optimcon, 'cgoptimconstraint')
    error(message('mbc:cgoptim:InvalidArgument'));
else 
    % Ensure that the existing constraint has the same name as the label
    optimcon = setName(optimcon, label);
end
    
optim.Constraints = [optim.Constraints, {optimcon}]; 
optim.ConstraintEnabled = [optim.ConstraintEnabled, true];
optim.oppoints = addConstraint(optim.oppoints);