Matlab's bsxfun() code

五迷三道 提交于 2019-12-02 00:09:13

问题


What does this do?

u = [5 6];
s = [1 1];
data1    =[randn(10,1) -1*ones(10,1)];
data2    =[randn(10,1) ones(10,1)];
data     = [data1; data2];
deviance = bsxfun(@minus,data,u);  
deviance = bsxfun(@rdivide,deviance,s); 
deviance = deviance .^ 2; 
deviance = bsxfun(@plus,deviance,2*log(abs(s)));
[dummy,mini] = min(deviance,[],2);

Is there an equivalent way of doing this without bsxfun?


回答1:


The function BSXFUN will perform the requested element-wise operation (function handle argument) by replicating dimensions of the two input arguments so that they match each other in size. You can avoid the use of BSXFUN in this case by replicating the variables u and s yourself using the function REPMAT to make them each the same size as data. Then you can use the standard element-wise arithmetic operators:

u = repmat(u,size(data,1),1);  %# Replicate u so it becomes a 20-by-2 array
s = repmat(s,size(data,1),1);  %# Replicate s so it becomes a 20-by-2 array
deviance = ((data-u)./s).^2 + 2.*log(abs(s));  %# Shortened to one line



回答2:


bsxfun does binary operations element wise. It's useful when you need to subtract a vector (in this case u) from all the elements along a particular dimension in a matrix (in this case data). The dimension along which the operation is being performed must match in both cases. For your example, you can incorporate the code without bsxfun as

u1=repmat(u,size(data,2),1);
deviance=data-u1;

and so on for the other operations.



来源:https://stackoverflow.com/questions/5382654/matlabs-bsxfun-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!