For a loop , to carry out element by element multiplication is bsxfun better than conventional element by element.

4 views (last 30 days)
for number of iterations
A = A.*B; %A and B both are complex
end
Will the loop be faster if I replace A.*B with bsxfun(@times,A,B) . Why?

Accepted Answer

Walter Roberson
Walter Roberson on 30 Aug 2018
Only in the circumstances that you are using R2016b or later and B has a different dimension than A, such as if A is 2d and B is a vector with the same number of rows as A has. Releases before that would return an error message in that situation, but starting R2016b MATLAB would use implicit expansion. Implicit expansion has been timed as no faster than bsxfun and typically a bit slower than bsxfun.
But in the case where the two array are the same size, bsxfun is expected to be slightly slower due to the overhead of testing to determine that regular operations can be used.
  4 Comments
Walter Roberson
Walter Roberson on 30 Aug 2018
I wonder how much of that is overhead of calling the anonymous function? The tradeoffs might depend on the number of columns possibly.
Walter Roberson
Walter Roberson on 31 Aug 2018
I am finding timing to be fairly comparable.
fimp = @() a.*b; tempf = @times; fbsx = @() bsxfun(tempf, a, b); rimp = zeros(1,100); rbsx = zeros(1,100); for K = 1 : 100; rimp(K) = timeit(fimp,0); end; for K = 1 : 100; rbsx(K) = timeit(fbsx, 0); end
plot([rimp.', rbsx.'])
legend('a.*b', 'bsxfun')
Neither one has a clear advantage.
Note:
Historically I have noticed in timings like this, that the first outer loop is often measurably slower -- so switching to calculate the other one first might make a distinct difference in the speeds. In cases where I see a quite noticeable difference in speeds between two approaches with the first one being slower, I repeat the code for the first one again later (except different output variable), and the second copy of testing exactly the same code is often much faster than the first copy. This happens even inside of functions that have been executed multiple times, so the time taking to JIT the code cannot be the explanation for those cases.

Sign in to comment.

More Answers (2)

Matt J
Matt J on 30 Aug 2018
No, it will not be faster.

Alan Weiss
Alan Weiss on 30 Aug 2018
Edited: Alan Weiss on 30 Aug 2018
Here are the results of one experiment that I just tried:
A = randn(1e4) + 1i*randn(1e4);
B = randn(1e4) + 1i*randn(1e4);
tic;C=A.*B;toc
Elapsed time is 0.450380 seconds.
tic;C=A.*B;toc
Elapsed time is 0.163965 seconds.
tic;C=bsxfun(@times,A,B);toc
Elapsed time is 0.823555 seconds.
tic;C=bsxfun(@times,A,B);toc
Elapsed time is 1.031081 seconds.
Alan Weiss
MATLAB mathematical toolbox documentation

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!