matlab函數 bsxfun淺談(轉載)

來源:互聯網
上載者:User

標籤:

關於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淺談(轉載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.