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

2 次查看(过去 30 天)
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?

采纳的回答

Walter Roberson
Walter Roberson 2018-8-30
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 个评论
Walter Roberson
Walter Roberson 2018-8-30
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 2018-8-31
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.

请先登录,再进行评论。

更多回答(2 个)

Matt J
Matt J 2018-8-30
No, it will not be faster.

Alan Weiss
Alan Weiss 2018-8-30
编辑:Alan Weiss 2018-8-30
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by