Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: avoiding loops to built a z matrix of the most efficient form
Date: Wed, 25 Mar 2009 16:44:02 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 46
Message-ID: <gqdn0i$a5r$1@fred.mathworks.com>
References: <gqdj93$qa4$1@fred.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1237999442 10427 172.30.248.37 (25 Mar 2009 16:44:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 25 Mar 2009 16:44:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:527663

"Jose " <jose.l.vega@gmail.com> wrote in message <gqdj93$qa4$1@fred.mathworks.com>...

> 
> You can see how using loops the algorithm run faster than the other without loops sugested by us.
> 

I can't see the point to optimize/benchmark for such a small-size problem, unless if you repeat it many time, but we haven't told that.

The overhead of calling functions are expensive, and not computation. In this case, just stick with the for-loop.

Otherwise, for big size here is one way:


%piece of code
tic
nrv=1000% random variable
nrp=1001 % number of 2D-points points.

v1=rand(nrp,2); % 2D-points
v2=rand(nrv,2); % 2D-parameters

% way 2: Using my algorithm with loops.

tic
z1=zeros(1,nrp);
zloop=zeros(1,nrv);

for j=1:nrv    
    for i=1:nrp
        z1(i)=v1(i,:)*v2(j,:)';
    end  
    zloop(j)=sum(z1)';
end
toc % 1.235350 seconds.


% way three

tic
z=sum(reshape(sum(bsxfun(@times,...
      reshape(v1,[nrp 1 2]),...
      reshape(v2,[1 nrv 2])),3),...
      [nrp nrv]),1);
toc % 0.029425 seconds.

% Bruno