What's an efficient way to do an element-wise multiplication of matrices with different sizes without a permutation or for loop?

I have a line of code that has to run mutliple times inside a larger loop so I'm trying to streamline it as much as possilbe. A simplified version of the problem is shown below. I'm trying to solve for matrix D without using a for loop or a permutation. I've found that a permutation uses quite a bit more time than even a for loop.
The code start with matrix A which is 255x181 and matrix B which is 255x10. I would like to do an element wise multiplication of each column of B by each column of A. That would be done 181 times for each column in B. The code below accomplishes that by replicating matrix B so that it has dimensions of 255x10x181 and then permutes it to have final dimensions of 255x181x10 and then that matrix is multiplied by A. Matlab automatically takes care of replicating matrix A to account for the third dimension. It seems like there should be a faster and more clever way to implement this. Thanks.
A = rand(255,181);
B = rand(255,10);
C = permute(repmat(B,1,1,181),[1 3 2]);
D = A.*C;

 Akzeptierte Antwort

Matt J
Matt J am 2 Sep. 2021
Bearbeitet: Matt J am 2 Sep. 2021
Well, if you have a recent version of Matlab, this should be about twice as fast.
[mb,nb]=size(B);
D=A.*reshape(B,mb,1,nb);

1 Kommentar

That worked, thanks! I didn't know reshape could be used like that, it's basically a permute without the hit on time.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021a

Gefragt:

am 2 Sep. 2021

Kommentiert:

am 2 Sep. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by