Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

bsxfun

Elementwise Function Application (Matlab Style)


Description

Apply a binary function elementwise.

Usage

bsxfun(func, x, y)

  arrayfun(func, ...)

Arguments

func

function with two or more input parameters.

x, y

two vectors, matrices, or arrays of the same size.

...

list of arrays of the same size.

Details

bsxfun applies element-by-element a binary function to two vectors, matrices, or arrays of the same size. For matrices, sweep is used for reasons of speed, otherwise mapply. (For arrays of more than two dimensions this may become very slow.)

arrayfun applies func to each element of the arrays and returns an array of the same size.

Value

The result will be a vector or matrix of the same size as x, y.

Note

The underlying function mapply can be applied in a more general setting with many function parameters:

mapply(f, x, y, z, ...)

but the array structure will not be preserved in this case.

See Also

Examples

X <- matrix(rep(1:10, each = 10), 10, 10)
Y <- t(X)
bsxfun("*", X, Y)  # multiplication table

f <- function(x, y) x[1] * y[1]     # function not vectorized
A <- matrix(c(2, 3, 5, 7), 2, 2)
B <- matrix(c(11, 13, 17, 19), 2, 2)
arrayfun(f, A, B)

pracma

Practical Numerical Math Functions

v2.3.3
GPL (>= 3)
Authors
Hans W. Borchers [aut, cre]
Initial release
2021-01-22

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.