How can I vectorize this loop?

1 回表示 (過去 30 日間)
Michael
Michael 2014 年 7 月 30 日
編集済み: Andrei Bobrov 2014 年 7 月 30 日
I am trying to remove a loop from my code without using repmat.
A and B are matrices that have the same number of rows, say m. Otherwise they have arbitrary column size.
Let
The loop I want to vectorize.
k = size(A, 2);
l = size(B, 2);
for t = 1:m
ARP = ARP + A(t,:)' * B(t,:)
end
Which is a sum of matrices size (kX1)X(1Xl) = kXl. I actually want the average so:
ARP = (1/m) * ARP
So far I have tried using repmat which balloons up the size of my matrices and in fact fails when the matrices get largish.
%Create copies of A stacked on top of each other to a depth of l
exA = repmat(A, l, 1); % (m * k)Xl
%Reshape it so that exA has each column of A cloned k times
exA = reshape(exA, m, k * l); % mX(k * l)
%Create copies of B stacked next to each other to a width k
exB = repmat(B, 1, k); % mX(l * k)
%Both matrices are now m X k*l so we can element-wise multiply
%and take the mean of the rows.
ARP = mean(exA .* exB, 1); % 1X(k * l)
ARP = reshape(ARP, l, k)';
I am also aware that repmat can be replaced in vectorizations with bsxfun, although it is not clear how to implement bsxfun in this case. I appreciate any help that gets me to an optimized solution and also illustrates techniques for vectorization that I can study for similar problems.
Thanks in advance Mike

採用された回答

Jian Wei
Jian Wei 2014 年 7 月 30 日
Please try the following code to see if it gives you the same result as your code.
ARP = (1/m)*A'*B;

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2014 年 7 月 30 日
編集済み: Andrei Bobrov 2014 年 7 月 30 日
ARP = mean(bsxfun(@times,permute(A,[2,3,1]),permute(B,[3,2,1])),3);
or
ARP = squeeze(mean(bsxfun(@times,A,reshape(B,size(B,1),1,[]))));

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by