简体   繁体   English

如何在Matlab中使此循环更快

[英]How to make this loop faster in matlab

I have to multiply arrays A and B element by element and calculate the sum of the first dimension, then returns the result in C . 我必须将数组AB逐个元素相乘并计算第一维的总和,然后在C返回结果。 A is a N -by- M -by- L matrix. AN × M × L矩阵。 B is a N -by- 1 -by- L matrix. BN × 1 × L矩阵。 N and M is lower than 30 , but L is very large. NM小于30 ,但L非常大。 My code is: 我的代码是:

C=zeros(size(B));
parfor i=1:size(A,2)
    C(i,1,:) = sum(bsxfun(@times, A(:,i,:), B(:,1,:)), 1);
end

The problem is the code is slow, anyone can help to make the code faster? 问题是代码很慢,任何人都可以帮助使代码更快? Thank you very much. 非常感谢你。

How about something along the lines of this: 这样的事情怎么样:

C = permute(sum(A.*repmat(B,1,M)),[2,1,3]);

This speeds computation on my PC up by a factor of ~4. 这样可以将我的PC上的计算速度提高约4倍。 Interestingly enough, you can actually speed up the computation by a factor of 2 (at least on my PC) simply by changing the parfor loop to a for loop. 有趣的是,只需将parfor循环更改为for循环,您实际上就可以将计算速度提高2倍(至少在我的PC机上)。

Taking the comments from Luis Mendo, I propose to use this command: 采纳Luis Mendo的评论,我建议使用以下命令:

C=reshape(sum(bsxfun(@times, A, B), 1), size(B))

I think this is the fastest. 我认为这是最快的。

If I understand correctly, just do this: 如果我正确理解,请执行以下操作:

C = squeeze(sum(bsxfun(@times, A, B)));

This gives C with size M x L. 这使C的大小为M xL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM