Is bsxfun really applied element-wise?

前端 未结 1 370
青春惊慌失措
青春惊慌失措 2021-01-21 14:53

Suppose that I have the following function:

function x = printAndKeepX(x, y)
    x
    y
end

and I invoke bsxfun like so:

相关标签:
1条回答
  • 2021-01-21 15:32

    The documentation also states that:

    fun must also support scalar expansion, such that if A or B is a scalar, C is the result of applying the scalar to every element in the other input array.

    In your case B is in fact a scalar, so your function is applied on A only once.

    The same applies when the input arrays are matrices. For example, consider a case where bsxfun is invoked with a matrix A={ aij } of size m×n and a vector B={ bij } of size m×1. B would be replicated n times along the second dimension, and the function would be called as follows:

    function([a11, ..., a1n], b1)
    function([a21, ..., a2n], b2)
    ...
    function([am1, ..., amn], bm)

    This results in n function calls for vector-scalar inputs rather then mn function calls for pairs of scalars. If the function is vectorized, it may be reflected in a possibly significant performance gain.

    0 讨论(0)
提交回复
热议问题