我正在运行以下代码
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
进行一些替代实现可能有助于大大加快速度,但我不知 Prop 体是如何实现的。有没有更好的方法来处理这个问题?谢谢!
最佳答案
如果您使用单例扩展而不是 repmat
,则可以减少运行时间,implicit (需要 Matlab 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
方法中,扩展数组是显式构造的,这需要内存分配。
关于arrays - 3d 矩阵中 `repmat` 和 `permute` 的更快替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566521/