bsxfun vs implicit expansion

9 views (last 30 days)
Bradley Treeby
Bradley Treeby on 7 Sep 2023
Answered: Gagan Agarwal on 20 Sep 2023
The MATLAB docs recommend that calls to bsxfun are replaced with direct calls to the functions and operators that support implicit expansion. I have seen this same recommendation in several places on the file exchange (etc). However, a simple benchmark (see attached) seems to show that bsxfun is noticably faster, at least for this particular use case I'm interested in (complex vector times a complex 2D or 3D matrix with relatively large dimensions). The output image below is running in MATLAB 2023a. I get the same trend under both Windows and Linux on both new and old hardware. Is this an expected result? I couldn't find many details of what actually happens under the hood for both of these approaches and when it might be better to use one over the other.
  7 Comments
Walter Roberson
Walter Roberson on 8 Sep 2023
Historically, some of the frequent volunteers have found that bsxfun was faster for some situations but not all; implicit expansion is faster for some operations.
As far as I know, there is no guideance from Mathworks as to when each of the two would be expected to be faster.
Joss Knight
Joss Knight on 8 Sep 2023
GPU is faster because consecutive operations can be fused in the implicit case. Not sure about the CPU case. I'll ask.

Sign in to comment.

Answers (1)

Gagan Agarwal
Gagan Agarwal on 20 Sep 2023
Hi Bradley,
I understand that you want to know the scenarios for which ‘bxfun is preferred and the scenarios for which use of implicit expansion is preferred.
In general, it has been observed that implicit expansion tends to be faster than bsxfun. This is especially true when working with GPUs, where implicit expansion often outperforms bsxfun. However, I couldn't find any specific scenarios that definitely determine when to use one over the other. Therefore, the best approach would be to decide on a case-to-case basis.
I hope this helps!

Categories

Find more on Parallel Computing Fundamentals in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!