bsxfun — Apply a binary function element-wise with MATLAB-compatible singleton expansion.
C = bsxfun(fun,A,B) applies binary function fun element-wise to A and B after expanding singleton dimensions to a common compatible size.
Syntax
C = bsxfun(fun, A, B)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
fun | Any | Yes | — | Binary function handle or callable text. |
A | Any | Yes | — | Left scalar or array input. |
B | Any | Yes | — | Right scalar or array input. |
Returns
| Name | Type | Description |
|---|---|---|
C | Any | Element-wise callback result after singleton expansion. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:bsxfun:InvalidFunction | The first input cannot be used as a binary function. | bsxfun: first input must be a function handle or callable name |
RunMat:bsxfun:InvalidInput | Input arrays use unsupported types for bsxfun scalar expansion. | bsxfun: inputs must be numeric, logical, complex, or character arrays |
RunMat:bsxfun:SizeMismatch | Input arrays are not compatible for singleton expansion. | bsxfun: input sizes are not compatible for singleton expansion |
RunMat:bsxfun:FunctionError | The binary function errors or does not return scalar-uniform values. | bsxfun: callback execution error |
RunMat:bsxfun:Internal | Internal output allocation or GPU gather fails. | bsxfun: internal error |
How bsxfun works
funcan be a function handle, closure, bound function handle, or callable text accepted byfeval.AandBcan be numeric, logical, complex, or character scalars or arrays.- Dimensions must either match or have length one. A singleton dimension can expand to a zero-length dimension, producing an empty output.
- The callback is invoked once per output element with scalar values from the expanded inputs.
- Callback outputs must be scalar numeric, logical, complex, or character values. Mixed logical/numeric/character outputs promote to numeric; complex outputs promote the entire result to complex.
- The result shape is the MATLAB implicit-expansion shape of
AandB. - gpuArray inputs are gathered and callbacks run on the host because arbitrary function handles cannot be fused safely.
Examples
Subtract column means from a matrix
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.Compare every column-vector value with every row-vector value
A = [8; 17; 20; 24];
B = [0 10 21];
C = bsxfun(@gt,A,B)Expected output:
C = logical 4-by-3 arrayUse a custom binary function
f = @(a,b) a - exp(b);
C = bsxfun(f,1:7,pi*[0 1/4 1/3].')Expected output:
% C contains every pairwise callback result.Using 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?⌄
MATLAB now supports implicit expansion for many operators directly, but bsxfun remains useful for older code and for applying custom binary callbacks.
Can callbacks return arrays?⌄
No. bsxfun collects one scalar result per expanded element. Use arrayfun or cellfun when you need non-scalar or non-uniform outputs.
Does bsxfun keep gpuArray inputs on the GPU?⌄
No. RunMat gathers gpuArray inputs for bsxfun because the callback can be arbitrary MATLAB code. Direct element-wise builtins such as plus, minus, and times are the provider-native path.
Related Math functions
Elementwise
abs · angle · complex · conj · double · erf · erfcinv · exp · expm1 · factorial · flintmax · gamma · gammaln · heaviside · hypot · idivide · imag · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · swapbytes · times · uint32
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · 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
Optim
coneprog · fminbnd · fminunc · fsolve · fzero · integral · linprog · lsqcurvefit · lsqnonlin · optimset · quad · secondordercone
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.