Logo Background

bsxfun

  • Written by matlabtutorialsmatlabtutorials No Comments Comments
    Last Updated: December 6, 2009

    bsxfun – Apply element-by-element binary operation to two arrays with singleton expansion enabled
    Syntax

    1
    
    C = bsxfun(fun,A,B)

    Description

    C = bsxfun(fun,A,B) applies an element-by-element binary operation to arrays A and B, with singleton expansion enabled. fun is a function handle, and can either be an M-file function or one of the following built-in functions:

    @plus Plus

    @minus Minus

    @times multiply

    @rdivide Right

    @ Left

    @power power

    @max Binary maximum

    @min Binary minimum

    @rem Remainder after division

    @mod Modulus after division

    @atan2 Four quadrant inverse tangent

    @hypot Square root of sum of squares

    @eq Equal

    @ne Not equal

    @lt Less than

    @le Less than or equal to

    @gt Greater than

    @ge Greater than or equal to

    @and Element-wise logical AND

    @or Element-wise logical OR

    @xor Logical exclusive OR

    If an M-file function is specified, it must be able to accept either two column vectors of the same size, or one column vector and one scalar, and return as output a column vector of the size as the input values.

    Each dimension of A and B must either be equal to each other, or equal to 1. Whenever a dimension of A or B is singleton (equal to 1), the is virtually replicated along the dimension to match the other . The may be diminished if the corresponding dimension of the other is 0.

    The size of the output C is equal to:

    1
    
    max(size(A),size(B)).*(size(A)>0 & size(B)>0).

    Examples

    In this example, bsxfun is used to subtract the column means from the corresponding columns of matrix A.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    A = magic(5);
    A = bsxfun(@minus, A, mean(A))
    A =
     
         4    11   -12    -5     2
        10    -8    -6     1     3
        -9    -7     0     7     9
        -3    -1     6     8   -10
        -2     5    12   -11    -4