fmincon — Find a constrained local minimum using interior-point, SQP, active-set or trust-region-reflective.
fmincon minimizes a real scalar objective subject to linear inequalities A*x<=b, linear equalities Aeq*x=beq, bounds lb<=x<=ub and nonlinear inequalities c(x)<=0/equalities ceq(x)=0. The default interior-point algorithm uses a primal-dual logarithmic barrier. Algorithm='sqp' selects conic quadratic subproblems; Algorithm='active-set' selects a primal working-set quadratic mechanism. The latter two share sequential-quadratic major iterations, exact-penalty globalization and Lagrangian BFGS, but not their quadratic objective solve. Trust-region-reflective uses distinct bound-reflected or equality-projected trust-region steps with supplied gradients. Sqp-legacy remains unimplemented, not an alias.
Syntax
[x,fval,exitflag,output,lambda,grad,hessian] = fmincon(fun,x0,A,b)
[...] = fmincon(fun,x0,A,b,Aeq,beq)
[...] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub)
[...] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)
[...] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)
[...] = fmincon(problem)Inputs
fun- Type
Any- Required
- Yes
- Default
- —
- Description
- Objective returning a scalar, optionally its gradient, and the selected reflective Hessian or Hinfo.
x0- Type
Any- Required
- Yes
- Default
- —
- Description
- Finite nonempty real starting array; its shape is preserved.
A- Type
Any- Required
- Yes
- Default
- —
- Description
- Sparse or dense linear inequality matrix, or [].
b- Type
Any- Required
- Yes
- Default
- —
- Description
- Linear inequality RHS vector, or [].
Aeq- Type
Any- Required
- Yes
- Default
- —
- Description
- Sparse or dense linear equality matrix, or [].
beq- Type
Any- Required
- Yes
- Default
- —
- Description
- Linear equality RHS vector, or [].
lb- Type
Any- Required
- Yes
- Default
- —
- Description
- Lower bound array, with -Inf for an absent bound.
ub- Type
Any- Required
- Yes
- Default
- —
- Description
- Upper bound array, with Inf for an absent bound.
nonlcon- Type
Any- Required
- Yes
- Default
- —
- Description
- Nonlinear constraint function returning [c,ceq] and optionally [GC,GCeq], or [].
options- Type
Any- Required
- Yes
- Default
- —
- Description
- Scalar supported options struct; default interior-point or explicit sqp/active-set/trust-region-reflective.
problem- Type
Any- Required
- Yes
- Default
- —
- Description
- Scalar structure with objective, x0, solver and options, plus optional constraints/bounds.
Returns
x- Type
Any- Description
- Last evaluated bound-feasible point, shaped like x0.
fval- Type
Any- Description
- Objective at x, or [] when no evaluation was permitted.
exitflag- Type
Any- Description
- 1 original KKT; 2 feasible small step; 3 feasible small function change; 0 limit; -1 observer; -2 local restoration failure; -4 numerical difficulty.
output- Type
Any- Description
- Actual iterations, evaluated points/callback counts, feasibility, first-order measure, algorithm and elapsed admitted clock.
lambda- Type
Any- Description
- Original-row multiplier estimates in six fields, or [] before an estimate is available.
grad- Type
Any- Description
- Already evaluated objective gradient column, or [] if unavailable.
hessian- Type
Any- Description
- Last-used SQP/active-set/reflective model, final-point interior-point BFGS model, or original reflective Hinfo; [] if unavailable.
Returned values from fmincon depend on how many outputs the caller requests.
Errors
RunMat:fmincon:InvalidArgument- When
- Invalid public grammar, unsupported algorithm/option, or invalid numeric/callback contract.
- Message
fmincon: invalid argument
Inputs and original geometry
FiniteDifferenceStepSize (legacy FinDiffRelStep) accepts a finite strictly positive real floating scalar or vector; a scalar factor expands to every variable. TypicalX must be a finite strictly positive real floating vector with one element per original variable (a scalar for a scalar problem).
Omitted or empty controls resolve to sqrt(eps) for forward differences, eps^(1/3) for existing central-difference routes, and unit TypicalX. Forward offsets use sign(x), with sign(0)=1, times the factor and max(abs(x),TypicalX); central offsets omit that sign. Actual representable bound-feasible offsets own the denominators. Nominal underflow uses adjacent representable feasible points; unusable actual offsets or an overflowing central span refuse before probe callbacks. These controls do not add objective calls or bypass existing evaluation budgets. Fully supplied derivative paths leave these operands dormant, without validating or gathering them.
Use fun,x0,A,b, optionally followed by complete Aeq/beq and lb/ub pairs, nonlcon and options. Empty constraint pairs mean no constraints; empty bounds mean unbounded components. A scalar problem struct requires objective, x0, solver='fmincon' and options, with optional Aineq,bineq,Aeq,beq,lb,ub,nonlcon. Omitting Algorithm selects interior-point; Algorithm='sqp' selects SQP.
x0 can be a finite real scalar or array. Every callback receives the original array shape, and returned x keeps that shape; linear constraint columns refer to column-major x(:). Linear matrices and analytic nonlinear Jacobians retain sparse CSC storage. Bounds can contain signed infinity, cannot contain NaN, and must be consistent. Shorter nonempty bound arrays constrain their leading components and issue a warning; remaining components are unbounded. SQP clips an outside starting component to the closest bound. Interior-point shifts a component on/outside a nonfixed bound into a representable strict interior, while fixed coordinates retain their exact bound value. If no finite representable interior exists, numerical difficulty is reported rather than probing outside the domain.
Callbacks and derivatives
By default fun returns a real scalar and nonlcon returns [c,ceq]. With SpecifyObjectiveGradient=true, fun returns [f,g], with numel(g)=numel(x0). With SpecifyConstraintGradient=true, nonlcon returns [c,ceq,GC,GCeq]; each Jacobian has numel(x0) rows and one column per corresponding constraint, including zero-column matrices for absent constraints. Constraint counts cannot change between evaluations.
Missing derivatives use actual bound-feasible forward differences, or centered differences with FiniteDifferenceType='central' (legacy FinDiffType). Fixed variables use zero feasible-direction differences. SpecifyConstraintGradient is effective only when nonlcon is present and SpecifyObjectiveGradient is true; otherwise its value is not inspected, gathered or invoked by numerical preparation, and constraint gradients are differenced. Objective and nonlinear-constraint callbacks at one point share a single MaxFunctionEvaluations point charge; output records their separate actual callback counts. A complete derivative sweep and trial cannot overrun this hard point budget. Callback exceptions and cancellation retain their original cause and never become numerical line-search retries. Only actual nonfinite/complex numerical trial values are treated as undefined trials.
Algorithms and supported options
Interior-point owns positive slack and inequality-dual generations, equality multipliers and a monotone barrier target. Its primal-dual Newton equations are solved by a sparse residual lift using the shared cooperative conic kernel, without forming a Jacobian Gram matrix or dense inverse. Original Newton-block residuals are checked independently; a fraction-to-boundary nonlinear logarithmic-barrier merit search preserves positivity and original domain bounds. A local lifted-system failure is never reported as proof that the original nonlinear problem is infeasible. Rejected trials require no finite-difference sweep, and same-point slack/dual centering reuses the already evaluated point without callback replay.
SQP solves a convex quadratic linearization with the shared cooperative sparse conic kernel and independently checks its original subproblem KKT residuals. Active-set first establishes a feasible quadratic point, then solves equality-constrained working-set models: a blocking inequality enters at the first boundary and an inequality with a negative multiplier leaves. All equality rows remain in the set. The original full quadratic rows, stationarity, dual signs and complementarity are checked before a step is accepted; a local numerical-work limit reports difficulty rather than inventing a solution. Phase-I feasibility and equality-constrained numerical solves reuse the cooperative kernel. Both sequential-quadratic algorithms use an exact-penalty line search and elastic restoration for incompatible local linearizations, without claiming global nonlinear infeasibility. A Powell-damped Lagrangian BFGS update supplies the next positive-semidefinite model.
Supported controls are Algorithm='interior-point'/'sqp'/'active-set', MaxIterations/MaxIter, MaxFunctionEvaluations/MaxFunEvals, OptimalityTolerance (legacy TolFun), ConstraintTolerance/TolCon, StepTolerance/TolX, FiniteDifferenceType/FinDiffType, Display, SpecifyObjectiveGradient, SpecifyConstraintGradient and OutputFcn. Interior-point defaults are 1000 iterations, 3000 evaluated points and StepTolerance=1e-10; SQP and active-set use 400 iterations, 100*numel(x0) points and StepTolerance=1e-6. All use optimality/constraint tolerances of 1e-6. Iteration/point limits and tolerances may be zero. OutputFcn uses the ordinary original-context init/iter/done observer contract and can request termination without replaying the objective. Display supports off, none, iter and final. Unimplemented controls are rejected rather than accepted and ignored.
General objective/constraint scaling, interior-point selectable Hessian approximations/functions and alternate subproblem algorithms, parallel differences, plotting, ObjectiveLimit/MaxTime, best-feasible diagnostic history and additional algorithm-specific controls are not implemented. Reflective Hessian and subproblem controls are described separately below. Sqp-legacy remains unavailable. These limitations mean this is partial fmincon API coverage, not full optimization-toolbox equivalence.
Trust-region-reflective
Algorithm='trust-region-reflective' requires SpecifyObjectiveGradient=true. It supports bounds alone, linear equalities alone, or an unconstrained problem. Linear inequalities, nonlinear constraints, combined bounds and linear equalities, and equal lower/upper bounds are not supported by this algorithm. Sparse matrices are supported. Bound starts are moved to a representable strict interior; equality starts are corrected using one retained sparse QR/COD factor. Every original equality row is checked, including redundant rows.
The bound algorithm uses a Coleman–Li scaled quadratic model and compares bound-limited, reflected and scaled-Cauchy trajectories. The equality algorithm projects the trust-region model onto the original linear null space. Conjugate gradients uses operator products and a band preconditioner, not a hidden dense inverse. SubproblemAlgorithm='factorization' or PrecondBandWidth=Inf selects explicit direct factorization; its matrix workspace is quadratic in the number of variables. The original model residual and original constraint/KKT checks remain the acceptance authority.
With HessianFcn=[], HessianMultiplyFcn=[] uses finite differences of supplied gradients. HessPattern is a symmetric real/logical dense or sparse structural pattern; graph coloring shares compatible probes. TypicalX and FiniteDifferenceStepSize do not apply to this algorithm. HessianFcn='objective' requests [f,g,H], with H a real symmetric matrix. Alternatively, HessianMultiplyFcn supplies W=hmul(Hinfo,Y), where [f,g,Hinfo]=fun(x). Hinfo is an original retained value, not converted into a numeric matrix. HessianMultiplyFcn requires HessianFcn=[] and the cg subproblem; direct factorization is not supported for this callback form. A selected objective Hessian leaves multiply/pattern controls dormant, and a selected multiply callback leaves the pattern dormant.
Reflective defaults are MaxIterations=400, MaxFunctionEvaluations=100*numel(x0), OptimalityTolerance=1e-6, FunctionTolerance=1e-6, StepTolerance=1e-6, SubproblemAlgorithm='cg', TolPCG=0.1 and PrecondBandWidth=0. MaxPCGIter defaults to max(1,floor(numel(x0)/2)) for bounds and numel(x0) for equalities. PrecondBandWidth accepts a nonnegative integer or Inf; MaxPCGIter and TolPCG are inactive in direct mode. Legacy TolFun names the function-change criterion here, independently of modern OptimalityTolerance. Conflicting bindings to the same criterion are refused. Known concrete defaults are inspectable; dimension-dependent defaults are resolved when the problem size is known.
Reflective output adds cgiterations and trustregionradius to the ordinary information fields. Flag 2 tests an accepted feasible relative step, and flag 3 tests accepted feasible relative function change; neither promises first-order optimality. The seventh output is the last-used Hessian model, or the original Hinfo for HessianMultiplyFcn, without building an unused successor or replaying callbacks. It is [] if no model was used. All gradient/Hessian probes and accepted or undefined evaluated trials obey the original hard point budget; service errors and callback exceptions are never numerical radius retries.
Outputs and stopping meaning
Up to seven outputs are [x,fval,exitflag,output,lambda,grad,hessian]. Outputs use already evaluated/constructed accepted-state data, never extra callback calls to fill missing outputs. fval/grad/hessian are [] if their value/model is unavailable. A finite-differenced bound-fixed coordinate has no full objective derivative available without an out-of-domain probe; grad marks that coordinate NaN. Internal zero feasible-direction slopes are not reported as full derivatives: first-order success/firstorderopt and full multiplier publication are withheld while required full derivatives are unavailable, but a genuine feasible-small-step stop remains possible. Analytic derivatives retain their actual fixed-coordinate values. Observer gradient is [] when its full objective derivative is unavailable.
SQP and active-set return the last-used step model (normally the next-to-last point), without constructing an unused dense successor on stop. Interior-point returns its chosen BFGS approximation at the final point. Neither is an exact objective Hessian, and [] is returned when no corresponding model was constructed.
Exitflag 1 requires original nonlinear feasibility and Lagrangian first-order, dual-sign and complementarity checks at the requested tolerances. Flag 2 means a feasible small step and flag 3 a feasible small function change, without promising first-order optimality. Flag 0 is a hard iteration/evaluated-point limit; -1 is observer termination; -2 is local restoration failure and is not a global nonlinear infeasibility proof; -4 is numerical difficulty without a minimum claim. Lambda is [] before a real multiplier estimate is available; otherwise its numeric columns ineqlin,eqlin,ineqnonlin,eqnonlin,lower,upper preserve original supplied row/variable identities. No elastic-objective dual is published as an original-objective multiplier.
The fourth output reports actual iterations, funcCount (evaluated points), objectiveCallCount, constraintCallCount, constrviolation, firstorderopt, stepsize, algorithm and message. When it is requested, wallclocktime uses the original invocation's admitted monotonic Clock port captured before input work. Missing Clock authority raises RunMat:Clock:ServiceUnavailable; no ambient or platform clock is substituted. Fewer than four requested outputs do not read that clock.
Execution and compatibility
This is a cooperative host solver on native and WebAssembly targets. Provider transfers, callback dispatch, cancellation and observer publication use the original runtime context. Transparent Automatic arrays can materialize under the ordinary policy; Explicit gpuArray input needs the named RunMat host-gather extension, and unproven resident intent is refused. No GPU numerical optimizer or distributed solver is claimed.
Interior-point and trust-region-reflective admit documented sparse numeric data/Jacobians without a RunMat sparse extension. Sparse SQP and active-set data/Jacobians remain a named extension because MATLAB's corresponding algorithms do not support sparse data. Single host data and exact native-integer/logical numeric data/results are separate RunMat extensions. Native-integer controls have their structural extension; ordinary floating controls do not require the Single-data extension. Conversion refuses integers not exactly representable as double. Strict compatibility checks apply before transfers to the affected role. Finite host-memory execution is unsupported and refused before solver/callback workspace; no complete finite-memory certificate is claimed.
Examples
Use a supplied gradient with reflective bounds
options=optimoptions('fmincon','Algorithm','trust-region-reflective',...
'SpecifyObjectiveGradient',true,'Display','off');
[x,fval,flag]=fmincon(@boundedquad,[0.5;0.5],[],[],[],[],[0;0],[1;2],[],options)
function [f,g]=boundedquad(x)
f=(x(1)-2)^2+(x(2)-1)^2;
g=2*(x-[2;1]);
endUse sparse equalities and an objective Hessian
options=optimoptions('fmincon','Algorithm','trust-region-reflective',...
'SpecifyObjectiveGradient',true,'HessianFcn','objective',...
'SubproblemAlgorithm','factorization','Display','off');
[x,fval,flag]=fmincon(@equalityquad,[0;0],[],[],sparse([1 1]),2,[],[],[],options)
function [f,g,H]=equalityquad(x)
f=sum((x-[3;2]).^2);
g=2*(x-[3;2]);
H=sparse(2*eye(2));
endSelect a working-set constrained step
fun=@(x)(x(1)-2)^2+(x(2)-1)^2;
options=optimoptions('fmincon','Algorithm','active-set','Display','off');
[x,fval,flag]=fmincon(fun,[0;0],[1 1],1,[],[],[0;0],[],[],options)Use the default barrier algorithm with bounds and an equality
fun=@(x)(x(1)-3)^2+(x(2)-2)^2;
[x,fval,flag]=fmincon(fun,[0.2;2],[],[],[1 1],2,[0;0],[1;4])Minimize with a linear inequality
fun=@(x)(x(1)-2)^2+(x(2)-1)^2;
options=optimoptions('fmincon','Algorithm','sqp','Display','off');
[x,fval,flag]=fmincon(fun,[0;0],[1 1],1,[],[],[],[],[],options)Constrain a local minimum to a disk
fun=@(x)(x(1)-2)^2+x(2)^2;
options=optimoptions('fmincon','Algorithm','sqp','Display','off');
[x,fval,flag]=fmincon(fun,[0.5;0],[],[],[],[],[],[],@unitdisk,options)
function [c,ceq]=unitdisk(x)
c=x(1)^2+x(2)^2-1;
ceq=[];
endUsing fmincon with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fmincon changes the result.
Run a small fmincon example, explain the result, then change one input and compare the output.
Related Math functions
Optim
acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
Elementwise
abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8
Trigonometry
acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Factor
chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. Read exactly how fmincon is executed, line by line, in Rust.
- View the source for fmincon in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.