- The binary function used by 'bsxfun' will no longer be an anonymous function, but instead the built-in 'rdivide'.
- The 'angle' call now operates on the entire matrix of combinations rather than individual entries.
Why is my call to "bsxfun" slower than a similar call using "repmat" in MATLAB (R2014b)?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
MathWorks Support Team
il 24 Mar 2015
Modificato: MathWorks Support Team
il 3 Mar 2021
I was under the impression that 'repmat' is typically slower than 'bsxfun' . However, I am comparing the two methods when performing the same computation using 'timeit' and I find that 'bsxfun' is slower:
>> x = 2*pi*rand(500,1);
>> y = x;
>> f1 = @() angle(repmat(exp(1i*x),1,length(y)) ./ repmat(exp(1i*y'),length(x),1));
>> timeit(f1)
ans =
0.0059
>> f2 = @() bsxfun(@(x,y)angle(x/y),exp(1i*x),exp(1i*y'));
>> timeit(f2)
ans =
0.0209
Why is 'repmat' faster in this case, and how can I improve the performance of 'bsxfun'?
Risposta accettata
MathWorks Support Team
il 3 Mar 2021
Modificato: MathWorks Support Team
il 3 Mar 2021
One contributing factor to the performance difference is the fact that the 'bsxfun' call is using an anonymous function handle rather than built-in functions. A second factor is that, as a result of the way the 'bsxfun' call is formulated, the 'angle' function is called many times, rather than being called once on a full matrix. By contrast, the 'repmat' version involves only one call to 'angle', which results in more efficient computation.
The performance of 'bsxfun' can be dramatically improved (and a more accurate comparison against 'repmat' can be made) by instead writing the 'bsxfun' call as:
>> angle(bsxfun(@rdivide,exp(1i*x),exp(1i*y')));
This formulation produces the same result, but has two advantages:
On the same machine that generating the timing numbers listed above, this formulation produces the following result:
>> f3 = @() angle(bsxfun(@rdivide,exp(1i*x),exp(1i*y')));
>> timeit(f3)
ans =
0.0036
From the results, the 'bsxfun' version is now faster than the 'repmat' version as one might expect.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!