Path: news.mathworks.com!not-for-mail
From: "Yi Cao" <y.cao@cranfield.ac.uk>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Vectorization
Date: Sun, 5 Jul 2009 19:07:00 +0000 (UTC)
Organization: Cranfield University
Lines: 46
Message-ID: <h2qtkk$2bh$1@fred.mathworks.com>
References: <8d98157c-ab47-40cb-8e4f-af119371a0db@h8g2000yqm.googlegroups.com> <491153fb-0184-4438-997d-cacf25797dea@i6g2000yqj.googlegroups.com>
Reply-To: "Yi Cao" <y.cao@cranfield.ac.uk>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1246820820 2417 172.30.248.38 (5 Jul 2009 19:07:00 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 5 Jul 2009 19:07:00 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 69713
Xref: news.mathworks.com comp.soft-sys.matlab:552914


laxxy <laxyfoxx@gmail.com> wrote in message <491153fb-0184-4438-997d-cacf25797dea@i6g2000yqj.googlegroups.com>...
> > > I am wondering if it is possible to eliminate the loop in the
> > > following piece of code:
> >
> > > for i=1:K
> > > ? W(i,:) = Q(i,:)*V(:,P(i,:));
> > > end;
> >
> > > (that is: each row i of the result is computed by multiplying ith row
> > > of matrix Q by a permutation of columns of V specified by the i'th row
> > > of P).
> >
> > W=Q*V(repmat((1:K)',1,N)+(P-1)*K);
> 
> Thanks!
> But this is not quite the same though: in your solution each row of
> the V(...) is permuted differently; but the i'th iteration of the loop
> computes the same permutation on all rows of V which is specified
> given by P(i,:)...

Bruno is right. Instead of permutating before multiplying, it should be after the production. Try the following code:

% prepare some data
K=10;
N=20;
Q=randn(K);
V=randn(K,N);
[Z,P]=sort(V,2); % produce some permutation

% vectorized
Z=Q*V;
Z=Z(repmat((1:K)',1,N)+(P-1)*K);

%original loop
W=zeros(K,N);
for i=1:K
W(i,:) = Q(i,:)*V(:,P(i,:));
end;

%compare difference
norm(W-Z)

% should be very small

HTH
Yi