標籤:
關於matlab函數 bsxfun
本文來源:http://blog.sina.com.cn/s/blog_9e67285801010ttn.html
a=[1 2 3];
b=[1 2 3]‘;
c=bsxfun(@plus,a,b)
c =
2 3 4
3 4 5
4 5 6
相當於:1 2 3 1 1 1
1 2 3 + 2 2 2
1 2 3 3 3 3
bsxfun的執行是這樣的,如果a和b的大小相同,那麼c=a+b. 但如果有某維不同,且a或b必須有一個在這一維的維數為1, 那麼bsxfun就將少的這個虛擬複製一些來使與多的維數一樣。在我們這裡,b的第一維只有1(只一行),所以bsxfun將b複製3次形成一個3×3的矩陣,同樣也將a複製成3×3的矩陣。這個等價於c=repmat(a,1,3)+repmat(b,3,1)。這裡
repmat(a,1,3) ans = -0.2453 -0.2453 -0.2453 -0.2766 -0.2766 -0.2766 -0.1913 -0.1913 -0.1913
repmat是顯式的複製,當然帶來記憶體的消耗。而bsxfun是虛擬複製,實際上通過for來實現,等效於for(i=1:3),for(j=1:3),c(i,j)=a(i)+b(j);end,end。但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 |
matlab函數 bsxfun淺談(轉載)