Matlab向量化编程的利器
bsxfun函数的用法
假设A是m*n维的矩阵,B是1*n维的行向量,现在希望A的每一行都加上B,则可用下面语句
bsxfun(@plus,A,B)
实际上该语句等效为
A+repmat(B,m,1)
即把B向量扩展为与A兼容的m*n维矩阵,然后再与A相加。但在bsxfun中,这个扩展的操作是内部虚拟进行的,并不实际占用内存,因此更快。
除了@plus,还有@time,@rdivide,等二元运算,具体用法参见文献2
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 |
参考文献: