simulannealbnd — Minimize an objective with a single-chain simulated annealing search.
Minimize an objective with a single-chain simulated annealing search.
Syntax
[x,fval,exitflag,output] = simulannealbnd(fun,x0)
[...] = simulannealbnd(fun,x0,lb,ub)
[...] = simulannealbnd(fun,x0,lb,ub,options)
[...] = simulannealbnd(problem)Inputs
fun- Type
Any- Required
- Yes
- Default
- —
- Description
- The actual selected objective returning one finite real double scalar.
x0- Type
Any- Required
- Yes
- Default
- —
- Description
- Nonempty finite double vector, or one opaque custom decision object.
lb- Type
Any- Required
- Yes
- Default
- —
- Description
- Double lower bounds; [] means unbounded.
ub- Type
Any- Required
- Yes
- Default
- —
- Description
- Double upper bounds; [] means unbounded.
options- Type
Any- Required
- Yes
- Default
- —
- Description
- Selected canonical annealing options or [].
problem- Type
Any- Required
- Yes
- Default
- —
- Description
- Complete objective,x0,lb,ub,solver='simulannealbnd',options and optional rngstate.
Returns
x- Type
Any- Description
- Best actually measured point, in the original double shape or original custom representation.
fval- Type
Any- Description
- Actual objective at x; [] if no objective was evaluated.
exitflag- Type
Any- Description
- 1 function stall,5 objective,0 budgets,-1 observer,-2 infeasible,-5 time.
output- Type
Any- Description
- iterations,funccount,message,initial rngstate,problemtype,temperature and totaltime.
Returned values from simulannealbnd depend on how many outputs the caller requests.
Errors
RunMat:simulannealbnd:InvalidArgument- When
- A problem, option, numerical result, callback return, or executable selected role is invalid.
- Message
simulannealbnd: invalid argument
Calling forms and results
Use simulannealbnd(fun,x0), simulannealbnd(fun,x0,lb,ub), or simulannealbnd(fun,x0,lb,ub,options). The one-argument problem form requires objective,x0,lb,ub,solver='simulannealbnd',options; rngstate is optional. An empty bound is unbounded. Short bounds apply to leading entries and warn; a scalar bound does not expand over a nonscalar x0.
fun is the selected name or handle and returns one finite real double scalar. Default x0 is a nonempty finite real double row/column; x retains its shape. Initial coordinates outside consistent bounds are projected into the interval. Inconsistent bounds return flag -2 without objective evaluation.
Request zero through four outputs [x,fval,exitflag,output]. x and fval are the best measured pair, not a replay for reporting. output has iterations, funccount,message,problemtype,temperature,totaltime,rngstate. Temperature is a column vector. rngstate is the invocation random stream state before algorithm draws; problem.rngstate restores that same random stream.
Flags: 1 is average objective change below FunctionTolerance over MaxStallIterations; 5 is a best value strictly below ObjectiveLimit; 0 is an iteration/evaluation limit; -1 is a logical observer stop; -2 is inconsistent bounds; -5 is MaxTime. A zero evaluation budget returns the feasible starting point and [] fval without inventing a measurement. A global-minimum certificate is not implied.
Algorithm and active options
Annealingfast takes a temperature-scaled isotropic direction; annealingboltz uses square-root temperature. A violated bound component is replaced by a uniform point between the violated bound and previous feasible coordinate. Improvements are accepted; otherwise acceptancesa uses the logistic probability 1/(1+exp((newf-oldf)/max(temperature))). Equal values have probability one half.
TemperatureFcn is temperatureexp (T0*.95^k), temperaturefast (T0/k), temperatureboltz (T0/log(k)), or a custom handle. InitialTemperature defaults to 100 and is a nonnegative scalar or positive vector matching x0. The annealing parameter starts at zero and advances before cooling. For Boltzmann startup, RunMat uses max(1,log(k)) as the denominator.
ReannealInterval defaults to 100 accepted proposals; zero disables reannealing. Double-domain sensitivities come from representable coordinate objective probes, counted in funccount and limited by the remaining evaluation budget. Finite bound widths scale sensitivities. Reannealing lowers k using the temperature/sensitivity logarithmic rule with safeguards for zero, infinite or otherwise unusable sensitivities, then cooling resumes.
MaxIterations defaults to Inf; MaxFunctionEvaluations defaults to 3000*numel(x0); MaxStallIterations defaults to 500*numel(x0). Counts are nonnegative exact structural integers; FunctionTolerance is nonnegative, default 1e-6. The stall window retains only scalar absolute current-value changes and computes a scaled mean. FunctionTolerance=0 disables the strict change test.
MaxTime is nonnegative seconds or a scalar duration, default Inf. ObjectiveLimit defaults to -Inf. The invocation Clock is required before RNG/objective/UI effects because total elapsed time and observer t0 are public. Limits act at iteration boundaries; in-flight callbacks are not interrupted or replayed.
Display is off/final/iter/diagnose, default final; DisplayInterval is positive, default 10. Diagnose adds the effective domain, dimensions and limits. Legacy option-structure names TolFun,MaxIter,MaxFunEvals,StallIterLimit,TimeLimit, OutputFcns,PlotFcns map to the same typed controls. Conflicting aliases reject. UseParallel and UseVectorized are not annealing controls and reject explicitly.
Custom roles, observers and hybrid
DataType='custom' retains an arbitrary decision payload, without walking fields, captures or properties. It requires a custom AnnealingFcn and forbids HybridFcn/numeric bounds. Only its outer extent supplies temperature dimensions. The proposal returns newx=f(optimValues,problem), where problem contains objective,x0,nvar,lb,ub. Double proposals are checked and repaired against the input bounds; custom payload representations remain opaque.
Custom acceptance is accept=f(optimValues,newx,newfval), returning logical scalar. Custom cooling is temperature=f(optimValues,options), returning the required finite nonnegative temperature vector. Function handles retain their selected definition; a custom handle named like a predefined function does not select the predefined implementation.
The public custom-data contract supplies no coordinate differential metric. RunMat's opaque-domain reannealing therefore uses the equal-sensitivity safeguard: the sensitivity ratio cancels, while accepted-point intervals and temperature-dependent reheating remain active. No fabricated numeric custom point is sent to the objective. This safeguard does not promise MATLAB's undocumented internal random trajectory or custom-data sensitivity heuristic.
OutputFcn uses [stop,options,optchanged]=f(options,optimValues,flag). PlotFcn uses stop=f(options,optimValues,flag). Both support cells; a nested callback/parameter cell appends those parameters. Flags are init,iter,done; stop and optchanged must be logical scalars. A changed options generation is validated before replacing the previous options; changing DataType mid-run rejects. Done returns do not relabel completed termination.
optimValues contains x,fval,bestx,bestfval,temperature,iteration,funccount,t0,k. Current and best points can differ. PlotInterval is positive, default one. The six saplot functions update receiver-backed point, objective, temperature or stopping-criteria charts. PlotFcn requires plot-core and an available UI service before objective evaluation; plots update the selected chart.
HybridFcn selects fminsearch,fminunc,fmincon,patternsearch, optionally paired with its own options. HybridInterval is end (default), never, or a positive iteration interval. Bounded problems require fmincon/patternsearch. A selected hybrid must be available before optimization starts. Its returned point, value and evaluation count are used without another objective call. The remaining outer evaluation budget is imposed on hybrid options and actual counts are included.
Execution boundary
CPU scans, proposals and callback boundaries use the invocation's work budget and cancellation state. RNG turns do not span user callbacks, so callbacks can use the same random stream. Callback and service errors stop the solve and retain their error identity.
Finite host-memory policies are unsupported and return an error before RNG, transfer, clock, UI or objective effects: the custom callback and solver workspace is not bounded. Selected explicit-resident and exact native-integer option controls require the corresponding RunMat extensions. Callback captures and opaque custom decisions are never automatically gathered. Double decision, bounds and objective data require concrete real full host double carriers.
Examples
Preserve original column shape at a zero iteration limit
opts=optimoptions('simulannealbnd','Display','off','MaxIterations',0);
[x,f,flag,out]=simulannealbnd(@(x)sum(x.^2),[2;3],[],[],opts);Optimize an opaque decision object through its actual proposal
opts=optimoptions('simulannealbnd','DataType','custom','Display','off','AnnealingFcn',@(v,p)struct('value',v.x.value-1),'AcceptanceFcn',@(v,x,f)true,'ReannealInterval',0,'MaxIterations',2);
[x,f,flag,out]=simulannealbnd(@(x)x.value^2,struct('value',2),[],[],opts);Using simulannealbnd with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how simulannealbnd changes the result.
Run a small simulannealbnd 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 · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · 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 simulannealbnd is executed, line by line, in Rust.
- View the source for simulannealbnd 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.