简体   繁体   中英

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 . A is a N -by- M -by- L matrix. B is a N -by- 1 -by- L matrix. N and M is lower than 30 , but L is very large. 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. 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.

Taking the comments from Luis Mendo, I propose to use this command:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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