我正在运行以下代码
a = normrnd(0,1,5000, 300);
b = normrnd(0, 1, 5000, 50);
tic
xp = repmat(a,1,1,50) .* permute(repmat(b, 1,1, 300), [1 3 2]);
toc哪种输出
Elapsed time is 0.425773 seconds.显然,大部分执行时间都花在了repmat和permute部分上。我认为bsxfun的一些替代实现可能有助于提高速度,但我看不出具体是如何实现的。有没有更好的方法来处理这个问题?谢谢!
发布于 2019-10-26 07:46:03
如果您使用单例扩展implicit (需要repmat R2016b或更高版本),则可以减少运行时间:
xp = a .* permute(b, [1 3 2]);或使用bsxfun显式
xp = bsxfun(@times, a , permute(b, [1 3 2]));在我的机器上,使用timeit (比tic,toc更精确)得到结果:
>> a = normrnd(0,1,5000, 300);
>> b = normrnd(0, 1, 5000, 50);
>> timeit(@() repmat(a,1,1,50) .* permute(repmat(b, 1, 1, 300), [1 3 2]))
ans =
0.706580436900000
>> timeit(@() a .* permute(b, [1 3 2]))
ans =
0.167270436900000
>> timeit(@() bsxfun(@times, a , permute(b, [1 3 2])))
ans =
0.161594036900000这些减少的时间可能的解释是,在repmat方法中,扩展数组是显式构造的,这需要内存分配。
https://stackoverflow.com/questions/58566521
复制相似问题