matlab-solve-optimization skill
Guides the full optimization lifecycle in MATLAB, including problem formulation, solver selection, configuration, and result validation.
- GitHub stars
- 1,293
- Files
- 9
- Last commit
- Nov 9, 2026
- License
- See LICENSE
- Allowed tools
- —
What does the matlab-solve-optimization skill do?
matlab-solve-optimization guides the full optimization lifecycle in MATLAB, including problem formulation, solver selection, configuration, and result validation.
Summary generated from the skill's SKILL.md.
About the matlab-solve-optimization skill
Managing the complete lifecycle of numerical optimization within MATLAB is the primary function of this skill. It assists developers and engineers in classifying mathematical problems, formulating them using either problem-based or solver-based approaches, and selecting the most appropriate algorithms for their specific needs. The skill provides guidance on using tools like optimproblem and optimvar for readable modeling, or transitioning to direct solver calls when performance or C code generation is required.
Users can utilize this skill to configure solvers such as fmincon, linprog, quadprog, and intlinprog by verifying valid options through optimoptions. It also provides methods for validating results by interpreting exitflags, checking constraint violations, and verifying gradients. Whether you are debugging convergence issues or attempting to improve performance through parallel computing or analytic gradients, this skill offers a structured workflow to move from initial problem definition to final solution verification.
What an agent can do with it
- 1Formulate optimization problemsDefine decision variables, objectives, and constraints using the problem-based approach in MATLAB.
- 2Select appropriate solversDetermine the most efficient solver for a specific problem class to ensure convergence and accuracy.
- 3Configure solver optionsSet up specific algorithm parameters and verify they are compatible with your installed MATLAB version.
- 4Validate optimization resultsCheck if a solution has converged and verify that all constraints are satisfied.
Written from the skill's SKILL.md. Every use case is checked against a quote from it.
How to install the matlab-solve-optimization skill
Each command copies the skill folder into the client's skills directory. Restart the client or start a new session to load it.Install the matlab-solve-optimization skill in Claude Code
~/.claude/skills/matlab-solve-optimization/SKILL.md
$ npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization ~/.claude/skills/matlab-solve-optimizationInstall the matlab-solve-optimization skill in Claude Code (project)
.claude/skills/matlab-solve-optimization/SKILL.md
$ npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization .claude/skills/matlab-solve-optimizationInstall the matlab-solve-optimization skill in Codex
~/.agents/skills/matlab-solve-optimization/SKILL.md
$ npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization ~/.agents/skills/matlab-solve-optimizationInstall the matlab-solve-optimization skill in Gemini CLI
~/.gemini/skills/matlab-solve-optimization/SKILL.md
$ npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization ~/.gemini/skills/matlab-solve-optimizationInstall the matlab-solve-optimization skill in Claude.ai
npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization matlab-solve-optimization && zip -r matlab-solve-optimization.zip matlab-solve-optimization # claude.ai → Customize → Skills → + → Create skill → Upload a skill → matlab-solve-optimization.zip
Automated checks
Ran Nov 15, 2026Full report →Not verified yet. A skill needs a score of 80, no serious finding, and enough data for us to check. How checks work
- Source repository linked and reachablematlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization is public and reachablegithub.com/matlab/matlab-agentic-toolkit/tree/HEAD/skills-ca ↗Pass
- Open source license (OSI)License named in a file, not as an SPDX idNot checked
- Commit or release in the last yearLast commit 2026-11-09github.com/matlab/matlab-agentic-toolkit/commits ↗Pass
- No download-and-run or credential theft in scriptsNo scripts in the skill folderPass
- No hidden instructions in SKILL.mdNo override phrases, safeguard switches, credential requests or hidden charactersgithub.com/matlab/matlab-agentic-toolkit/blob/HEAD/skills-ca ↗Pass
- Pre-approved tools are scopedNo pre-approved tools; the agent asks before using onegithub.com/matlab/matlab-agentic-toolkit/blob/HEAD/skills-ca ↗Pass
- SKILL.md follows the Agent Skills formatValid name and description; says when to use it; 289 linesgithub.com/matlab/matlab-agentic-toolkit/blob/HEAD/skills-ca ↗Pass
SKILL.md
View on GitHubMATLAB Optimization Workflow
Guide the full optimization lifecycle: classify the problem, formulate it, select and configure a solver, and validate the results.
When to Use
- User is defining an optimization problem in MATLAB (variables, objectives, constraints)
- User asks about
optimproblem,optimvar,optimconstr,optimexpr, orfcn2optimexpr - User is selecting or configuring a solver (
optimoptions, algorithm choice, tuning) - User is interpreting results, debugging convergence, or checking exitflags
- User is deciding between problem-based and solver-based approaches
- User is writing optimization code with for-loops over decision variables or constraints
When NOT to Use
- User is asking to solve a problem that doesn't require numerical optimization solvers (e.g., finding the minimum value in an array or table)
- User is working with non-optimization MATLAB code (data analysis, plotting, signal processing)
- User is using a third-party optimization toolbox (not MathWorks)
- User is solving symbolic equations with
solve(eqns, vars), ODE systems, or linear system solves (A\b)
Stage 1: Classify & Formulate
1.1 Classify the Problem
Before formulating, identify the problem class — it determines which solver to use, what guarantee you can promise (global vs local), and whether a domain-specific tool should replace the generic path.
See references/classify.md for the class→solver→guarantee table, convexity quick-checks, and "hidden easier class" heuristics. Key actions:
- Check if a purpose-built domain tool exists before falling back to
optimproblem - Watch for hidden easier classes (sum-of-squares disguised as NLP, linear structure missed)
- For QPs, check
eig(H)— nonconvex QPs cannot usequadprogreliably - Watch for hidden nonsmoothness:
max,min,abs,sort,if/branching, or norms other than squared-2-norm
1.2 Choose Approach
Use problem-based by default for readable definitions, N-D modeling, and every LP, QP, conic, and mixed-integer problem (unless coefficients are already in matrix-vector form). Problem-based provides automatic differentiation and is less error-prone.
Even when AD is blocked (e.g., ode45 in the objective), fcn2optimexpr can still wrap the function as a black-box — problem-based remains useful.
Only fall back to solver-based when one of these applies:
| Use solver-based when... | Reason |
|---|---|
Trivial mapping to solver API — one vector x, pre-coded objective with exact gradients/Hessian |
No benefit from abstraction; solver-based is direct |
| Overhead of building problem-based expressions dominates computation | Avoid tracing/transformation overhead |
Need a solver feature problem-based doesn't expose (CheckpointFile, exact Hessians, custom OutputFcn) |
Only available via solver-based calls |
| C code generation for embedded deployment is required | Problem-based does not support codegen |
Converting between approaches: prob2struct(prob) converts problem-based to solver-based form for deployment or performance.
References:
- Problem-based: references/problem-based-guide.md
- Solver-based (class→solver mapping): references/classify.md
1.3 Formulate the Problem
Problem-based canonical template:
% 1. Define decision variables
x = optimvar("x", N, LowerBound=lb, UpperBound=ub);
% 2. Create problem
prob = optimproblem("Objective", sum(x,"all"));
% 3. Add constraints
prob.Constraints.linear = A*x <= b;
prob.Constraints.nonlinear = fcn2optimexpr(@myNonlinFcn, x) <= rhs;
% 4. Set initial guess (must be struct with field names matching optimvar names)
x0.x = initialValues;
% 5. Solve
[sol, fval, exitflag, output] = solve(prob, x0);
Solver-based key differences:
- Initial guess is a numeric vector, not a struct
- You manage variable indexing manually (flat vector
x) - Supply gradients manually for best performance (
SpecifyObjectiveGradient=true) - Linear/quadratic solvers require explicit coefficient matrices
1.4 Validate at the Start Point
Before calling any solver, evaluate the objective and constraints at x0 to catch sign/size/NaN errors early:
% Problem-based
fval0 = evaluate(prob.Objective, x0);
assert(isfinite(fval0), 'Objective is not finite at x0');
infeas0 = infeasibility(prob.Constraints, x0);
fprintf('Max infeasibility at x0: %.3e\n', max(infeas0));
For solver-based, call fun(x0) and nonlcon(x0) directly and confirm finite, correctly-sized outputs. If gradients are supplied, run checkGradients at this point.
Stage 2: Select & Configure Solver
2.1 Select the Narrowest Solver
Choose the narrowest solver that matches the problem structure. Do not default to fmincon or heuristic global solvers when a more specific solver applies.
Key selection rules:
- Always prefer:
linprog>quadprog>coneprog>lsqlin>lsqnonlin>fmincon> global solvers - Always prefer
fminuncoverfminsearchwhen Optimization Toolbox is installed - Always prefer
lsqnonlin/lsqcurvefitoverfminconfor least-squares problems - Always prefer
lsqlinoverlsqnonlinfor linear least-squares with bounds or linear constraints - Use
patternsearchwhen gradients are unavailable/unreliable AND the problem is not extremely expensive - Use
surrogateoptwhen each evaluation takes >15-20 seconds - For nearly linear MIPs, linearize and use
intlinprograther than calling Global Optimization solvers - For unit commitment / binary operating modes, keep mixed-integer with
intlinprog
See references/classify.md for the full class→solver table.
2.2 Verify Options — Never Guess
ALWAYS verify that solver options are valid before using them. Options change across MATLAB releases and hallucinated options cause runtime errors.
% Verify options for a solver
opts = optimoptions('solvername')
Run optimoptions('solvername') to see all valid options for the user's installed version before writing options code.
2.3 Verify Gradients (if supplied)
If analytic gradients are supplied (SpecifyObjectiveGradient=true), verify them before solving:
[valid, err] = checkGradients(@myObjective, x0, Display="on");
For constraint gradients: checkGradients(@myConstraints, x0, IsConstraint=true).
2.4 Parallelize (if expensive)
If the solver supports UseParallel and Parallel Computing Toolbox is available:
ver('parallel') % Check for PCT
options = optimoptions('solvername', UseParallel=true);
Solvers supporting UseParallel: fmincon, fminunc, lsqnonlin, lsqcurvefit, patternsearch, surrogateopt, ga, particleswarm, paretosearch, gamultiobj.
Do NOT suggest UseParallel for: quadprog, intlinprog, fminsearch, linprog, lsqlin.
2.5 Performance (after correctness)
If the solve is correct but too slow, see references/performance-levers.md. Key levers: analytic gradients, sparsity patterns, warm starting, code generation. Apply only after Stage 3 confirms correctness — re-validate after any performance change.
Reference: references/solver-tuning.md for per-solver algorithm and tuning guidance.
Stage 3: Validate Results
3.1 Basic Validation (Always Include)
Every time solver-calling code is written, add basic output validation:
[sol, fval, exitflag, output] = solve(prob, x0);
% Check convergence
if exitflag > 0
fprintf('Optimization converged: %s\n', output.message);
else
warning('Optimization did not converge (exitflag = %d): %s\n', exitflag, output.message);
end
% Report key metrics
fprintf('Objective value: %.6f\n', fval);
fprintf('Iterations: %d\n', output.iterations);
if isfield(output, 'constrviolation')
fprintf('Constraint violation: %d\n', output.constrviolation);
end
See references/validation-checklist.md for detailed exitflag meanings per solver.
3.2 Extended Validation
Constraint violations (problem-based):
[allsat, sat] = issatisfied(prob, sol);
if ~allsat
conNames = fieldnames(prob.Constraints);
for i = 1:numel(conNames)
infeas = infeasibility(prob.Constraints.(conNames{i}), sol);
if any(infeas > 0)
fprintf('Constraint "%s" violated by %.3e\n', conNames{i}, max(infeas));
end
end
end
Optimality conditions (gradient-based solvers only — skip for patternsearch, ga, particleswarm, surrogateopt):
if isfield(output, 'firstorderopt')
fprintf('First-order optimality: %.6e\n', output.firstorderopt);
if output.firstorderopt > 1e-3
warning('First-order optimality measure is large — solution may not be optimal.\n');
end
end
3.3 Debugging Failed or Poor Solutions
When exitflag <= 0 or convergence is poor, follow the improving-results checklist in references/improving-results.md:
- Check formulation — constraints feasible? bounds consistent? objective well-defined at x0?
- Check scaling — scale variables to O(1); rescale if objective/constraints differ by orders of magnitude; use
FiniteDifferenceType='central'if finite-difference gradients are inaccurate - Try different algorithms —
options.Algorithm, increaseMaxIterations/MaxFunctionEvaluations, adjust tolerances, setHybridFcnfor heuristic solvers - Try different initial points —
MultiStart,GlobalSearch, orsurrogateopt/gafor global optimization
Debug discipline:
- Smallest-first. Shrink to 2-3 variables. A bug in a toy problem is minutes; at full scale is hours.
- One change at a time, justified by a symptom.
- Stop-and-ask budget. Stop coding and talk to the user when: >3 rounds with no improvement, >2 option tweaks that don't move diagnostics, or you can't get a finite objective at x0 even on a toy problem.
3.4 Application-Specific Visualization
| Problem Domain | Suggested Plots |
|---|---|
| Optimal control / navigation | State trajectories vs time, control input profiles, phase portraits |
| Scheduling / assignment | Gantt charts, resource utilization over time |
| Design optimization | Contour plots with optimum marked, sensitivity plots |
| Parameter estimation / fitting | Residual plots, fitted surface vs data |
| Portfolio / allocation | Bar charts of allocations, efficient frontier plots |
Gotchas
Formulation
- Initial guess must be a struct with field names matching
optimvarnames exactly. NOT a flat vector. - Do NOT set
SpecifyObjectiveGradientorSpecifyConstraintGradientin options for problem-based — AD manages gradients internally. - Use N-D
optimvarfor multi-dimensional problems. Do NOT create scalar variables in a loop. - Preallocate constraint arrays with
optimconstr(N). Do NOT concatenate in a loop. - Call
fcn2optimexprONCE per function, not inside loops. See references/fcn2optimexpr-guide.md. - Use
"like"for preallocation inside traced functions to preserve AD type:zeros(n,1,"like",x).
Solver Configuration
- Never guess option names from memory. Always verify with
optimoptions('solvername'). - Do NOT tighten
MeshToleranceforpatternsearchtoo much. - Do NOT set
AbsoluteGapTolerance/RelativeGapTolerancehigh forintlinprogfor early stopping — use time/node limits. - Keep tolerances well above machine epsilon. Use
1e-6to1e-8range unless specifically required.
Validation
output.constrviolationdoes not exist for unconstrained solvers. Always check withisfield.- Do NOT check
output.firstorderoptfor derivative-free solvers. Check solver-specific metrics instead (output.meshsize,output.stallgenerations). infeasibility()operates on individual constraints, not entire problems. Useissatisfied(prob, sol)for overall checks.- For
fminconwithexitflag <= 0, checkoutput.bestfeasible. Use it as a starting point for a new solve.
Conventions
- Default to problem-based unless a specific blocker applies.
- When vectorization is possible, always prefer it over loops.
- When wrapping complex logic in
fcn2optimexpr, encapsulate in a single helper function rather than calling inside a loop. - Always show the initial guess setup.
- Mark code blocks as templates when they depend on user-supplied functions.
- When suggesting tuning options, explain the trade-off (speed vs accuracy).
- Do not over-tune: for simple or small problems, defaults are usually sufficient.
- Always include basic validation (exitflag check) when writing solver-calling code.
- When debugging, start with formulation and scaling before changing algorithms.
Copyright 2026 The MathWorks, Inc.
Files in this skill
9matlab-solve-optimization skill questions
How do I install the matlab-solve-optimization skill in Claude Code?
Run npx degit matlab/matlab-agentic-toolkit/skills-catalog/math-and-optimization/matlab-solve-optimization ~/.claude/skills/matlab-solve-optimization. Claude Code loads skills from ~/.claude/skills (all projects) or .claude/skills (one project) and uses a skill when its description matches the task.
Which clients can use the matlab-solve-optimization skill?
Any client that reads the Agent Skills format: Claude Code, Codex, Gemini CLI and claude.ai (upload as a ZIP). Scripts in the skill run only where the client allows code execution.
Should I use problem-based or solver-based approaches in MATLAB?
Use problem-based by default for readable definitions and automatic differentiation. Only fall back to solver-based if you need specific features like C code generation, custom OutputFcn, or if the overhead of building expressions dominates computation.