【发布时间】:2022-01-03 11:35:36
【问题描述】:
我在搜索这个主题时确实碰到了this的问题,但是这个似乎已经过时了。
阅读https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b,2016b引入了隐式扩展,但我仍然可以在论文中找到参考代码使用bsxfun进行算术扩展。所以我假设在某些情况下,bsxfun 比其他方法更可取。
我确实比较了bsxfun、repmat 和隐式扩展之间的速度(我使用了来自link 的 Jonas 的代码)
下面是使用tictoc计算时间的对比:
这表明隐式扩展明显快于bsxfun 或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"])
【问题讨论】:
-
另请注意,隐式扩展似乎做了一些(意外)optimizations
bsxfun不做