particleswarm — Minimize a scalar objective with a genuine adaptive-neighborhood particle swarm.
Minimize a scalar objective with a genuine adaptive-neighborhood particle swarm.
Syntax
[x,fval,exitflag,output,points] = particleswarm(fun,nvars)
[...] = particleswarm(fun,nvars,lb,ub)
[...] = particleswarm(fun,nvars,lb,ub,options)
[...] = particleswarm(problem)Inputs
fun- Type
Any- Required
- Yes
- Default
- —
- Description
- Actual objective function handle or scalar function name; scalar rows or vectorized population rows.
nvars- Type
Any- Required
- Yes
- Default
- —
- Description
- Positive integer-valued double number of variables.
lb- Type
Any- Required
- Yes
- Default
- —
- Description
- Real double lower bounds or [].
ub- Type
Any- Required
- Yes
- Default
- —
- Description
- Real double upper bounds or [].
options- Type
Any- Required
- Yes
- Default
- —
- Description
- Canonical particleswarm options or [].
problem- Type
Any- Required
- Yes
- Default
- —
- Description
- objective,nvars,lb,ub,options,solver='particleswarm', and optional rngstate.
Returns
x- Type
Any- Description
- Best actually measured finite real row, optionally improved by the selected hybrid; [] for inconsistent bounds.
fval- Type
Any- Description
- Actual objective value at x, without reporting replay; [] before evaluation.
exitflag- Type
Any- Description
- 1 relative best-value stall; 0 iterations; -1 observer; -2 bounds; -3 objective limit; -4 stall time; -5 time.
output- Type
Any- Description
- iterations, funccount, message, hybridflag and original initial rngstate.
points- Type
Any- Description
- Actual final swarm: X has one row per particle; Fval contains its actual measurements, not personal bests or the hybrid point.
Returned values from particleswarm depend on how many outputs the caller requests.
Errors
RunMat:particleswarm:InvalidArgument- When
- A solver/control/objective carrier or geometry is invalid, or a selected numerical operation is not representable.
- Message
particleswarm: invalid argument
Forms and data
Forms are particleswarm(fun,nvars), particleswarm(fun,nvars,lb,ub), particleswarm(fun,nvars,lb,ub,options), and particleswarm(problem). The scalar problem has objective, nvars, lb, ub, options, solver='particleswarm', and optional rngstate. fun is a selected function handle or scalar function name. nvars is a positive integer-valued double; problem coordinates and bounds are real full host doubles. Bounds flatten in column-major order; [] is unbounded. A scalar bound expands, while a shorter nonscalar bound leaves trailing coordinates unbounded with a warning. Inconsistent bounds return x=[], fval=[] and flag -2 without objective, custom creation, RNG or plot effects.
Scalar objectives receive one 1-by-nvars row. With UseVectorized=true they receive an M-by-nvars matrix and return M actual double measurements; M can be one. The numerical comparison score accepts only finite real values. FunValCheck='on' rejects complex, Inf or NaN measurements; with 'off', undefined particles cannot win. Malformed carriers, callback errors, cancellation and provider errors remain errors, not undefined scores. An entirely undefined initial swarm cannot establish an incumbent and fails truthfully.
Up to five outputs are x, fval, exitflag, output and points. x is the best actual row and fval its actual measurement, optionally improved by the hybrid. output contains iterations, funccount, message, hybridflag, rngstate and swarmObjectiveCallCount. funccount includes actual measured particle points plus the hybrid's actual reported evaluations; the separate swarm call count distinguishes vectorized batches. points.X/Fval remain the actual final swarm, not individual historical bests or a hybrid point. Reporting never calls fun again.
Algorithm and effective controls
The algorithm maintains current positions, velocities and each particle's best actually measured position. A random adaptive neighborhood supplies the social target. The inertia-weighted velocity adds independent uniform personal and social components. Positions are clipped to bounds; an outward velocity at a clipped bound is reset. Successful generations lower the stall counter, restore the minimum neighborhood and adapt inertia; unsuccessful generations grow the neighborhood. This is not a local solver alias and does not certify a global minimum.
SwarmSize is an integer greater than one, default min(100,10*nvars). InertiaRange is an increasing same-sign finite pair, default [0.1,1.1]. MinNeighborsFraction is in [0,1], default .25. SelfAdjustmentWeight and SocialAdjustmentWeight are finite scalars, default 1.49 each. MaxIterations defaults to 200*nvars. MaxStallIterations is positive, default 20. FunctionTolerance is nonnegative, default 1e-6; a strict relative best-value change over the retained stall window triggers flag 1. Zero disables this strict function-change test.
ObjectiveLimit defaults to -Inf and triggers flag -3 on a strictly lower actual best value. MaxTime and MaxStallTime default to Inf; nonnegative seconds or genuine scalar duration values are accepted. Finite limits require the original admitted Clock before effects. Limits are checked at generation boundaries and do not interrupt an in-flight callback. Flags -5 and -4 distinguish elapsed and no-improvement time; flag 0 is the iteration limit and -1 a logical observer stop.
InitialPoints is an M-by-nvars double matrix or a scalar structure with X and optional Fval. A short population is filled; an oversized one uses its prefix. Supplied measurements are reused only for exactly unchanged supplied coordinates; clipping or a custom creation mismatch invalidates them. Missing measurement entries invoke the actual objective. InitialSwarm and InitialSwarmMatrix are legacy aliases of the same canonical InitialPoints identity. InitialSwarmSpan is a positive scalar or nvars-vector, default 2000, controlling one-sided/unbounded creation intervals and initial velocity ranges. Uniform creation uses both finite bounds as its interval.
CreationFcn is pswcreationuniform or one actual handle called as swarm=f(problem). The dimension-resolved problem.options.SwarmSize is available. OutputFcn accepts handles/cells; PlotFcn accepts handles/cells or the real predefined pswplotbestf name. Both use stop=f(optimValues,state), with init/iter/done and funccount,bestx,bestfval,iteration,meanfval,stalliterations,swarm,swarmfvals. Every return must be logical scalar. A done stop is validated without relabeling completed termination. The current population shares authoritative Tensor backing; a retained predecessor triggers cooperative copy-on-write, not eager per-callback mirroring.
UseParallel is off/auto/on; true maps to auto and false to off. UseVectorized=true has precedence, leaving parallel carriers inactive. Selected parallel execution uses the existing original-source CallbackBatch with bounded waves; there is no serial replay after partial acceptance or failure. Auto falls back only on known ineligibility or absent pool. On requires actual worker authority. HybridFcn is empty or fminsearch,fminunc,fmincon,patternsearch by name/selected handle, optionally paired with options in a cell. It runs only after flag 1. Bound problems require fmincon or patternsearch. The actual selected source is preserved, and a missing executable hybrid refuses before effects.
Display is off/none/final/iter, default final; DisplayInterval is positive, default one. Creation truncation is reported in iterative display. Console/diary and plot operations use original authority. The helper plot has receiver-backed history and requires plot-core/UI; closing targets does not fabricate a replacement.
Execution boundary
The host solver cooperates through scans, random proposals, objective and observer boundaries using the original CPU budget and cancellation authority. Random turns are short and never cross user code, so an objective can itself draw random values. output.rngstate records the default original stream before the algorithm; problem.rngstate restores through that same typed owner. No random stream is invented for deterministic reporting.
Finite host-memory policies refuse before preparation, transfer, RNG, UI or objective effects because no complete resource bound exists for the full population/callback/hybrid workspace. Selected numeric options may use authenticated automatic-residency gathers; explicit resident controls and exact native-integer controls require their declared original-context RunMat extensions. Captures and inactive controls are not recursively gathered. Objective results require double class; automatic-residency results can be gathered, while explicit or unproven result placement requires explicit gather. No GPU-native algorithm or silent typed-integer problem-data overload is claimed.
Examples
Return actual final swarm values
opts=optimoptions('particleswarm','Display','off','SwarmSize',4,'InitialPoints',[-1;0;1;2],'MaxIterations',0);
[x,f,flag,out,points]=particleswarm(@(x)x(1)^2,1,-2,2,opts);Evaluate one vectorized generation
opts=optimoptions('particleswarm','Display','off','SwarmSize',3,'InitialPoints',[-1 1;0 0;1 -1],'UseVectorized',true,'MaxIterations',0);
[x,f,flag,out,points]=particleswarm(@(x)sum(x.^2,2),2,[-2 -2],[2 2],opts);Using particleswarm with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how particleswarm changes the result.
Run a small particleswarm 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 · 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 particleswarm is executed, line by line, in Rust.
- View the source for particleswarm 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.