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: