当前位置:   article > 正文

Matlab bsxfun函数解析_matlab bxsfun

matlab bxsfun
bsxfun是一个matlab自版本R2007a来就提供的一个函数,作用是”applies an element-by-element binary operation to arrays a and b, with singleton expansion enabled。

bsxfun的执行效果是这样的,以两个变量a+b为例,如果a和b的各维度大小相同,那么c=a+b. 但如果有某维大小不同,且a或b必须有一个在这一维度的大小为1, 那么bsxfun就将维度大小为一的这个虚拟的复制一些来使与多的维数大小一样。

举例:

>> a = randn(3,1), b = randn(1,3)

a =

    0.5377
    1.8339
   -2.2588


b =

    0.8622    0.3188   -1.3077

>> bsxfun(@plus,a,b)

ans =

    1.3998    0.8564   -0.7700
    2.6961    2.1527    0.5262
   -1.3967   -1.9401   -3.5665

>> a = randn(4,3), b = randn(1,3)

a =

   -0.4336   -1.3499    0.7147
    0.3426    3.0349   -0.2050
    3.5784    0.7254   -0.1241
    2.7694   -0.0631    1.4897


b =

    1.4090    1.4172    0.6715

>> bsxfun(@plus,a,b)

ans =

    0.9754    0.0673    1.3862
    1.7517    4.4521    0.4665
    4.9874    2.1426    0.5474
    4.1785    1.3541    2.1612

>> a = randn(4,3), b = randn(2,3)

a =

   -1.2075    1.0347   -0.7873
    0.7172    0.7269    0.8884
    1.6302   -0.3034   -1.1471
    0.4889    0.2939   -1.0689


b =

   -0.8095    1.4384   -0.7549
   -2.9443    0.3252    1.3703

>> bsxfun(@plus,a,b)
Error using <u>bsxfun</u>
Non-singleton dimensions of the two input arrays must match each other.
 
>> 

以上操作也可以通过repmat函数来进行事先,但是repmat函数会复制矩阵,增加了额外的内存和时间。bsxfun是虚拟的复制,实际上通过for来实现,但bsxfun不会有使用matlab的for所带来额外时间。

附:

C = bsxfun(fun,A,B) appliesthe element-by-element binary operation specified by the functionhandlefun to arrays A and B,with singleton expansion enabled.fun can be oneof the following built-in functions:
@plus Plus
@minus Minus
@times Array multiply
@rdivide Right array divide
@ldivide Left array divide
@power Array 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


参考:

http://www.cnblogs.com/hxsyl/p/4429316.html

http://blog.sina.com.cn/s/blog_9e67285801010ttn.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/902552
推荐阅读
相关标签
  

闽ICP备14008679号