quadprog — Minimize a quadratic objective with linear constraints and bounds.
quadprog minimizes 0.5*x'*H*x + f'*x with A*x<=b, Aeq*x=beq and lb<=x<=ub using interior-point-convex or active-set.
Syntax
[x,fval,exitflag,output,lambda] = quadprog(H,f,A,b,Aeq,beq,lb,ub,x0,options)
[x,fval,exitflag,output,lambda] = quadprog(problem)
[wsout,fval,exitflag,output,lambda] = quadprog(H,f,A,b,Aeq,beq,lb,ub,ws)Inputs
H- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Real symmetric positive semidefinite quadratic coefficient matrix, dense or sparse.
f- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Linear objective coefficients; [] is the zero vector.
A- Type
NumericArray- Required
- No
- Default
- —
- Description
- Linear inequality coefficients.
b- Type
NumericArray- Required
- No
- Default
- —
- Description
- Linear inequality right-hand sides.
Aeq- Type
NumericArray- Required
- No
- Default
- —
- Description
- Linear equality coefficients.
beq- Type
NumericArray- Required
- No
- Default
- —
- Description
- Linear equality right-hand sides.
lb- Type
NumericArray- Required
- No
- Default
- —
- Description
- Lower bounds; omitted trailing elements are unbounded.
ub- Type
NumericArray- Required
- No
- Default
- —
- Description
- Upper bounds; omitted trailing elements are unbounded.
x0- Type
NumericArray- Required
- No
- Default
- —
- Description
- Validated initial point; ignored by interior-point-convex.
options- Type
Any- Required
- No
- Default
- —
- Description
- Consumed quadprog options or [].
problem- Type
Any- Required
- Yes
- Default
- —
- Description
- Scalar problem struct with H, f, solver, options and optional constraint fields.
H- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Original quadratic matrix.
f- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Original linear coefficients, or [].
A- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Inequality matrix, or [].
b- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Inequality right-hand sides, or [].
Aeq- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Equality matrix, or [].
beq- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Equality right-hand sides, or [].
lb- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Lower bounds, or [].
ub- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Upper bounds, or [].
ws- Type
Any- Required
- Yes
- Default
- —
- Description
- Immutable QuadprogWarmStart supplying X and active-set Options.
Returns
x- Type
Any- Description
- Decision column, or a new immutable QuadprogWarmStart in the ws form; evaluated current iterate on an active-set stop, empty on terminal failure.
fval- Type
NumericArray- Description
- 0.5*x'*H*x + f'*x, or [] when unavailable.
exitflag- Type
NumericScalar- Description
- Verified optimization status.
output- Type
Any- Description
- Actual iteration, algorithm and numerical diagnostic information.
lambda- Type
Any- Description
- Recovered original-row eqlin/ineqlin/lower/upper multipliers at a verified optimum; [] otherwise.
Returned values from quadprog depend on how many outputs the caller requests.
Errors
RunMat:quadprog:InvalidArgument- When
- Invalid arity or requested output count.
- Message
quadprog: invalid argument
RunMat:quadprog:InvalidInput- When
- Invalid numeric geometry, problem fields, or unsupported option.
- Message
quadprog: invalid input
Observable solver timing
When the fourth output struct is requested, output.wallclocktime is a numeric elapsed duration from the original invocation's admitted monotonic Clock service, captured before input materialization and the solve. A declared deterministic clock supplies its logical duration; this field is not independent physical profiling evidence. Missing clock authority raises RunMat:Clock:ServiceUnavailable before provider access or solver work; no ambient/platform clock or fabricated zero is substituted. Calls requesting fewer than 4 outputs do not read or require this clock unless a finite active-set MaxTime is selected. MaxTime and diagnostic elapsed time share the same solver clock origin. The canonical Clock effect is narrowed only when requested output count is statically known below that threshold.
Inputs
Use quadprog(H,f), then optional complete A,b and Aeq,beq and lb,ub pairs, followed by optional x0 and options (2, 4, 6, 8, 9 or 10 arguments). [] denotes an omitted pair, bound or initial point. f=[] denotes zero linear coefficients. H is a nonempty real square matrix. Non-symmetric H emits a warning and uses its symmetric part. f, lb and ub accept two-dimensional matrix arguments in column-major order; output x is a column. Right-hand sides and x0 are vectors. Short bounds leave the unspecified trailing variables unbounded and emit a warning.
The problem-struct form requires H, f, solver='quadprog' and options, with optional Aineq, bineq, Aeq, beq, lb, ub and x0. Other problem fields are ignored. x0 is validated but does not initialize the default interior-point-convex algorithm.
For interior-point-convex, H, A and Aeq retain sparse compressed-column storage. Active-set accepts dense public operands and rejects sparse operands before numerical input transfer; its internal row/factor representation remains compact. Finite bounds contribute single-entry rows, not dense identities. Double is the ordinary host input class. Ordinary-host Single data normalization to double, native-integer data per role and native-integer numeric options are gated RunMat extensions; MATLAB restricts Single to code generation/UseCodegenSolver. Native integers must be exactly representable as double. Single floating numeric controls remain ordinary scalar controls; the Single extension applies to data operands, not those controls. Logical, complex and object operands are rejected.
Authenticated automatically resident numeric arrays gather transparently through the original invocation context. Explicit gpuArray data and selected numeric controls use a separately gated RunMat host-gather extension, not device optimization; unknown/unproven intent refuses. Datatype and intent compatibility gates for all needed numeric roles and selected controls precede the first transfer; geometry and finite-value validation remain at their numerical owners.
Algorithm and controls
The default algorithm is interior-point-convex. H must be positive semidefinite; a negative certificate returns exitflag -6, never a clamped Hessian or a claimed convex optimum. Admission first checks diagonal dominance, then rigorously verifies a sparse numerical Cholesky proposal; ambiguous and semidefinite cases use exact sparse rational elimination. Exact sparse fill and rational bit growth can be expensive on ill-conditioned models.
optimoptions('quadprog') produces Algorithm='interior-point-convex', MaxIterations=200, OptimalityTolerance=1e-8, ConstraintTolerance=1e-8 and Display='final' (stored legacy names MaxIter, TolFun, TolCon). Interior-point tolerances must be positive finite. Active-set tolerances are nonnegative finite, including zero; no floor relaxes the request. MaxIterations is an exact nonnegative u32 count, including zero, shared by any auxiliary feasibility phase. Display supports off/none, iter and final. Unsupported controls reject rather than being ignored.
Algorithm='active-set' uses feasible primal working sets, equality-constrained original H/f targets through rank-revealing QR/COD, original-row blocking and deterministic multiplier release. Dependent equality rows are allowed. H may be indefinite outside the equality affine space if its restriction to null(Aeq) is positive semidefinite; exact equality elimination and sparse Schur checks decide this condition. Inconsistent equalities require their own infeasibility certificate, not a full-rank assumption.
Active-set controls and warm starts
Active-set defaults are MaxIterations=10*(n + number of stored linear/bound rows), OptimalityTolerance=1e-8, ConstraintTolerance=1e-8, StepTolerance=1e-8, ObjectiveLimit=-1e20 and MaxTime=Inf. A default MaxIterations is stored as [] until dimensions are known; an explicitly supplied count is not replaced. All feasibility and working-set phases share that count. A blocked recession proposal advances to the nearest real blocking row without an arbitrary unit-step horizon.
StepTolerance stops when a small step cannot establish the requested KKT conditions; it does not certify convergence. ObjectiveLimit stops only at a feasible point whose objective is below the threshold. For a problem-based maximization, the solver compares the signed minimization objective, including its original constant. MaxTime accepts nonnegative seconds or a scalar duration and uses the original admitted Clock; it is a soft boundary checked at numerical progress points, not hard preemption. StepTolerance, ObjectiveLimit and MaxTime are selected active-set controls and reject on the current interior-point implementation.
[wsout,fval,exitflag,output,lambda]=quadprog(H,f,A,b,Aeq,beq,lb,ub,ws) takes a QuadprogWarmStart from optimwarmstart(x0,options), where options selects active-set quadprog. Supply all eight numerical positions with [] for omissions; do not append options or place ws in a problem struct. Read the solution from wsout.X. The result is a new immutable object; aliases of ws remain unchanged.
Warm state retains X, Options and actual active linear/bound rows, not an objective, numerical factorization, certificate, runtime or allocation grant. Each call uses current H/f and establishes current feasibility before reusing only unchanged tight rows with matching typed roles. A changed equality discards the saved working set. The variable count must match; class and solver profiles must match.
Trust-region-reflective, Hessian multiplication callbacks, OutputFcn, FunctionTolerance, LinearSolver/ScaleProblem selection and code-generation options remain unsupported, not aliases. Single/code-generation support, finite factorization and warm-object transport remain separate limits of this interface.
Outputs and execution
[x,fval,exitflag,output,lambda] returns actual numerical outputs. exitflag 1 requires original-model primal, stationarity, cone-sign, gap and complementarity checks at the requested tolerances. 0 means an iteration or time limit; -2 requires an exact original infeasibility certificate. Interior-point -3 requires an exact flat recession direction H*d=0 and an exact feasible anchor. Active-set also permits a projected-flat ray: exact d'*H*d=0, equality tangency, homogeneous inequality/bound feasibility and negative (H*x+f)'*d at an exact feasible anchor. Recovery proposes candidates but does not prove them. Active-set ObjectiveLimit can also return raw flag -3 as a threshold stop; its message distinguishes that stop from certified unboundedness. Problem-based solve maps this threshold to ObjectiveLimitReached, not Unbounded. -6 means the selected curvature condition failed; -8 indicates numerical difficulty or unverified evidence.
lambda at a verified optimum contains recovered numeric column fields ineqlin, eqlin, lower and upper in original constraint and variable order. Failed/stopped solves do not manufacture multipliers. Terminal failures return empty x, fval and lambda; inconsistent bounds retain a supplied x0 while fval and lambda are empty. An interior-point stopped solve returns x/fval only for a feasible iterate. Active-set returns the actual finite evaluated current point and its objective on ordinary stops, even when phase one has not established feasibility; constrviolation and exitflag must be checked. These evaluated-only coordinates confer no feasibility or optimality certificate. Unestablished numerical metrics are NaN, not zeros.
output contains iterations, algorithm, linearsolver, constrviolation, firstorderopt, dualitygap, wallclocktime and message. firstorderopt is the normalized original KKT stationarity residual; constrviolation is the absolute original maximum constraint violation. wallclocktime measures elapsed input preparation, solve and validation time, including cooperative host turns. The solver checks cancellation and cooperates during traversal and between kernel iterations; an individual sparse factorization is synchronous, not hard-preemptible. Native and WASM use the same solver. No device or distributed QP solver is provided. Finite host-memory execution is unsupported and rejected before gather or workspace allocation.
Examples
Solve a convex constrained quadratic
H=[1 -1;-1 2]; f=[-2;-6]; A=[1 1;-1 2;2 1]; b=[2;2;3];
[x,fval,flag,output,lambda]=quadprog(H,f,A,b)Use an equality-constrained problem struct
problem.H=[1 -1;-1 2]; problem.f=[-2;-6]; problem.Aeq=[1 1]; problem.beq=0;
problem.solver='quadprog'; problem.options=optimoptions('quadprog','Display','off');
[x,fval,flag]=quadprog(problem)Restrict indefinite curvature with an equality
options=optimoptions('quadprog','Algorithm','active-set','Display','off');
[x,fval,flag]=quadprog([-1 0;0 2],[0;-4],[],[],[1 0],1,[],[],[1;0],options);Release a saved active bound for a new objective
options=optimoptions('quadprog','Algorithm','active-set','Display','off');
ws=optimwarmstart(4,options); old=ws;
[first,f1,flag1]=quadprog(1,1,[],[],[],[],0,[],ws);
[second,f2,flag2]=quadprog(1,-2,[],[],[],[],0,[],first);Using quadprog with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how quadprog changes the result.
Run a small quadprog 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 · fmincon · 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 · 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 quadprog is executed, line by line, in Rust.
- View the source for quadprog 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.