1. 程式人生 > >Matlab bsxfun函式解析

Matlab bsxfun函式解析

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:
@plusPlus
@minusMinus
@timesArray multiply
@rdivideRight array divide
@ldivideLeft array divide
@powerArray power
@maxBinary maximum
@minBinary minimum
@remRemainder after division
@modModulus after division
@atan2Four quadrant inverse tangent
@hypotSquare root of sum of squares
@eqEqual
@neNot equal
@ltLess than
@leLess than or equal to
@gtGreater than
@geGreater than or equal to
@andElement-wise logical AND
@orElement-wise logical OR

@xorLogical exclusive OR

參考:

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

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