bsxfun — Apply a binary function element-wise with singleton expansion.
bsxfun expands compatible singleton dimensions, calls a binary function once for each result position, and collects uniform scalar results in the expanded shape.
Syntax
C = bsxfun(fun, A, B)Inputs
fun- Type
Any- Required
- Yes
- Description
- Binary function handle; callable text is a RunMat-only extension.
A- Type
Any- Required
- Yes
- Description
- Left scalar or array input.
B- Type
Any- Required
- Yes
- Description
- Right scalar or array input.
Returns
C- Type
Any- Description
- Uniform scalar callback results in the singleton-expansion shape.
Errors
RunMat:bsxfun:InvalidFunction- When
- The first input cannot be used as a binary function.
- Message
bsxfun: first input must be a function handle or callable name
RunMat:bsxfun:InvalidInput- When
- An input cannot supply scalar numeric, logical, complex, or character values.
- Message
bsxfun: inputs must be numeric, logical, complex, or character arrays
RunMat:bsxfun:SizeMismatch- When
- Input dimensions are incompatible for singleton expansion.
- Message
bsxfun: input sizes are not compatible for singleton expansion
Singleton expansion
C = bsxfun(fun,A,B) aligns trailing dimensions of A and B. Corresponding dimensions must be equal or one; singleton dimensions expand to the other extent, including compatible zero-length extents.
The callback receives one scalar from each expanded position and must return one scalar. RunMat collects a numeric, logical, complex, or character result only when every callback result has the same class.
Callable and class behavior
fun may be a builtin, source function, local or nested function, bound function handle, or anonymous function. A scalar text name is available in RunMat compatibility mode and is rejected by the MATLAB compatibility pin.
Input scalar extraction preserves double, single, all eight fixed-width integer classes, logical, complex, and character values. The callback owns its argument admission, conversions, overflow behavior, effects, and output class.
Static analysis queries the typed callable contract with scalarized input facts. A builtin handle therefore receives the same argument-dependent inference as a direct builtin call; unresolved or shadowable names remain dynamic.
Accelerated inputs
The current implementation gathers provider-resident inputs through their owning providers, executes callbacks on the host, and returns a host value. This is a compatibility gap for GPU callbacks rather than a RunMat extension.
Use direct element-wise operators when provider-native execution and resident output are required. bsxfun is a fusion boundary because an arbitrary callback may suspend, throw, or perform other declared effects.
Examples
Subtract each column mean
A = [1 2 10; 3 4 20; 9 6 15];
C = bsxfun(@minus, A, mean(A))Expected output:
C has the same size as A and each column has mean zeroCompare a column with a row
A = [8; 17; 20; 24];
B = [0 10 21];
C = bsxfun(@gt, A, B)Expected output:
C is a logical 4-by-3 arrayUse an anonymous binary callback
f = @(a,b) a - exp(b);
C = bsxfun(f, 1:7, pi*[0 1/4 1/3].')Expected output:
C contains every pairwise callback resultPreserve fixed-width integer callback results
base = uint64(2^53);
A = [base + uint64(1); base + uint64(3)];
C = bsxfun(@plus, A, uint64([1 2]))Expected output:
C is an exact uint64 2-by-2 arrayRetain the callback class for an empty result
A = zeros(0, 3);
C = bsxfun(@gt, A, [1 2 3])Expected output:
C is an empty logical 0-by-3 arrayUsing bsxfun with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how bsxfun changes the result.
Run a small bsxfun example, explain the result, then change one input and compare the output.
FAQ
Should new code use bsxfun?⌄
Implicit expansion is clearer for ordinary element-wise operators. bsxfun remains useful for existing code and for binary callbacks that are not written as a direct operator expression.
Can the callback return an array?⌄
No. Each invocation must return one scalar, and all invocations must return the same class. Use arrayfun or cellfun for their corresponding mapping contracts.
How is an empty result typed?⌄
A typed builtin callback uses its catalog inference contract. A callable whose result cannot be established without execution remains dynamically typed and uses the runtime's compatibility fallback.
Does bsxfun keep gpuArray input resident?⌄
Not currently. Inputs are gathered through their exact owner and callback execution produces a host result. Direct supported operators provide the provider-native path.
Related Math functions
Elementwise
abs · angle · besselj · 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
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 · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
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 bsxfun is executed, line by line, in Rust.
- View the source for bsxfun 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.