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?
댓글 수: 0
채택된 답변
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
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
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개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!