fminsearch — Minimize a real scalar objective with Nelder-Mead simplex search.
x = fminsearch(fun,x0) performs derivative-free unconstrained search from a nonempty finite real double array. The objective receives x with the original shape; x retains that shape. No derivative, convexity or global-minimum guarantee is assumed.
Syntax
x = fminsearch(fun, x0)
x = fminsearch(fun, x0, options)
x = fminsearch(problem)
[x, fval] = fminsearch(...)
[x, fval, exitflag] = fminsearch(...)
[x, fval, exitflag, output] = fminsearch(...)
[x, fval, exitflag, output] = fminsearch(problem)Inputs
fun- Type
Any- Required
- Yes
- Default
- —
- Description
- Real scalar objective callback.
x0- Type
Any- Required
- Yes
- Default
- —
- Description
- Nonempty finite real double initial array.
options- Type
Any- Required
- No
- Default
[]- Description
- Legacy optimset options structure or [].
problem- Type
Any- Required
- Yes
- Default
- —
- Description
- Scalar structure with objective, x0, solver and optional options.
Returns
x- Type
Any- Description
- Best evaluated point, preserving x0 shape.
fval- Type
Any- Description
- Objective at x.
exitflag- Type
Any- Description
- 1: simplex converged; 0: budget; -1: observer stop.
output- Type
Any- Description
- iterations, funcCount, algorithm and message.
Returned values from fminsearch depend on how many outputs the caller requests.
Errors
RunMat:fminsearch:InvalidArgument- When
- Invalid argument, unsupported option, class or objective contract.
- Message
fminsearch: invalid argument
RunMat:fminsearch:InvalidFunctionValue- When
- FunValCheck is on and the objective returns NaN.
- Message
fminsearch: invalid objective value
RunMat:fminsearch:AllocationFailed- When
- Fallible host simplex/callback backing allocation fails.
- Message
fminsearch: workspace allocation failed
- When
- OutputFcn/PlotFcns is not a supported callback form or does not return a logical scalar stop flag.
- Message
fminsearch: invalid observer contract
Forms and controls
Supported forms are fminsearch(fun,x0), fminsearch(fun,x0,options), and fminsearch(problem), where problem has objective, x0, solver='fminsearch', and optional options. fun is a function handle or function name. Up to four outputs are x, fval, exitflag, and output with iterations, funcCount, algorithm and message. Use optimset, not optimoptions('fminsearch').
The eight legacy controls are Display, FunValCheck, MaxFunEvals, MaxIter, OutputFcn, PlotFcns, TolFun and TolX; case-insensitive unambiguous abbreviations are accepted. Empty numeric [] means the default. TolX and TolFun default to 1e-4 and must be positive; both absolute simplex spreads must pass to converge. Both budgets default to 200*numberOfVariables. MaxIter accepts a nonnegative integer-valued floating scalar; zero evaluates only the starting point, reports zero iterations and does not construct the remaining simplex. MaxFunEvals must be a positive integer-valued floating scalar. The literal dimension-dependent default from optimset('fminsearch') is decoded without evaluating arbitrary expressions. Unsupported nonempty options are rejected, not ignored.
The initial simplex adds 5% to each nonzero coordinate and 0.00025 to zero coordinates. Reflection, expansion, outside/inside contraction and shrink use the general Nelder-Mead algorithm. Only completed simplex operations count as iterations; every actual objective call counts, including a partially initialized or shrunk simplex. Hard evaluation limits are never exceeded. Flag 1 means both finite simplex spreads pass, not a mathematical minimum certificate; 0 means a budget limit and -1 means an observer stop. The best actually evaluated point is returned on budget or requested stop.
FunValCheck='on' rejects objective NaN. With 'off' (default), NaN ranks after ordinary values and cannot establish convergence. Inf is permitted in either setting but cannot establish finite simplex convergence. Objectives must return one real single or double value; complex, logical and typed-integer results are not admitted.
OutputFcn accepts a handle or cell array of handles. PlotFcns accepts a handle, name, or cell array of handles/names. Each callback receives (x,optimValues,state), with iteration, funccount, fval and procedure, and states init, iter and done. Each must return a logical scalar stop flag. Init/iter stop requests are combined; a done return is validated but does not relabel completed termination. original errors and cancellation propagate without callback replay. Init follows the first evaluation; iter follows each complete simplex operation; done follows normal completion or stop. Plot callbacks use separate invocation-owned axes, selected before every callback; graphics support requires plot-core. The predefined optimplotx, optimplotfunccount and optimplotfval helpers are real graphics, not console stand-ins.
Display defaults to notify (nonpositive termination only). final writes a terminal summary; iter writes an initial row and a row per complete simplex operation plus the summary; off/none are silent. Presentation uses the original invocation console/diary route and adds no objective calls. RunMat does not promise byte-identical MATLAB console layout.
Execution and supported boundary
The solver uses host binary64 arithmetic. x0 must be real dense double; objective/control scalars may be real single or double. Original Automatic-residency numeric values may be gathered; explicit or unproven device intent is refused before provider transfer. There is no provider-native solver or typed-integer/logical overload. Callback captures remain rooted in their original invocation and are not recursively gathered as option metadata.
Finite host-memory execution is currently unsupported: requests with a finite policy fail before derivative-free callbacks, metadata materialization or simplex/history/result allocation. Ordinary unbounded execution is unchanged. Cancellation and cooperative yielding are checked through long scans, sorting, simplex work and callback boundaries; no extra objective evaluation is used for reporting.
Examples
Minimize the Rosenbrock function
f = @(x) 100*(x(2)-x(1)^2)^2+(1-x(1))^2;
opts = optimset('Display','off');
[x,fval,flag,out] = fminsearch(f,[-1.2 1],opts)Preserve a matrix-shaped search variable
target = [1 2;3 4];
f = @(x) sum(sum((x-target).^2));
opts = optimset('TolX',1e-7,'TolFun',1e-10,'MaxFunEvals',4000,'MaxIter',2000,'Display','off');
x = fminsearch(f,zeros(2),opts)Using fminsearch with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fminsearch changes the result.
Run a small fminsearch example, explain the result, then change one input and compare the output.
FAQ
Does simplex convergence prove a minimum?⌄
No. Exitflag 1 reports finite TolX and TolFun simplex spreads; Nelder-Mead can stagnate and does not certify local or global optimality.
Which option constructor should I use?⌄
Use optimset. fminsearch is intentionally not an optimoptions solver identity.
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 · 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 fminsearch is executed, line by line, in Rust.
- View the source for fminsearch 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.