我确实碰到了this https://stackoverflow.com/questions/12951453/in-matlab-when-is-it-optimal-to-use-bsxfun在搜索这个主题时提出问题,但这似乎已经过时了。
Reading https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b,隐式扩展是在2016b引入的,但是我仍然可以在论文中找到参考代码bsxfun
用于算术扩展。所以我假设有一些情况使得bsxfun
优于其他方法。
我确实比较了之间的速度bsxfun
, repmat
,以及隐式扩展(我使用了 Jonas 的代码link https://stackoverflow.com/questions/12951453/in-matlab-when-is-it-optimal-to-use-bsxfun)
下面显示了使用时的计算时间比较tic
toc
:
这表明隐式扩展明显快于bsxfun
or repmat
。有什么理由使用bsxfun
如今?
这是我用来比较速度的代码:
n = 300;
k=100; %# k=100 for the second graph
a = ones(10,1);
rr = zeros(n,1);
bb = zeros(n,1);
ntt = 100;
tt = zeros(ntt,1);
for i=1:n;
r = rand(1,i*k);
for it=1:ntt;
tic,
x = bsxfun(@plus,a,r);
tt(it) = toc;
end;
bb(i) = median(tt);
for it=1:ntt;
tic,
y = repmat(a,1,i*k) + repmat(r,10,1);
tt(it) = toc;
end;
rr(i) = median(tt);
for it=1:ntt;
tic,
z = a + r;
tt(it) = toc;
end;
gg(i) = median(tt);
end
figure;
plot(bb,'b')
hold on
plot(rr,'r')
plot(gg,'g')
legend(["bsxfun","repmat","implicit"])