Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: avoid loops
Date: Tue, 24 Mar 2009 18:01:05 +0000 (UTC)
Organization: Univ of Newcastle upon Tyne
Lines: 61
Message-ID: <gqb751$a7m$1@fred.mathworks.com>
References: <gq84j5$oj7$1@fred.mathworks.com> <gq87ja$9ug$1@fred.mathworks.com> <gq8h69$rfp$1@fred.mathworks.com> <gq8kmp$9lb$1@fred.mathworks.com> <gq8pm5$2n3$1@fred.mathworks.com> <gqauop$s8r$1@fred.mathworks.com> <gqb21p$isa$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1237917665 10486 172.30.248.35 (24 Mar 2009 18:01:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 24 Mar 2009 18:01:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1511480
Xref: news.mathworks.com comp.soft-sys.matlab:527345

"us " <us@neurol.unizh.ch> wrote in message <gqb21p$isa$1@fred.mathworks.com>...
> "Jose "
> > I cannot find how I can vectorizing a z(3x2) matrix, 
> > maybe with repmat or reshape?
> > x=rand(nrp,2) % 2D- dimensional data
> > a=rand(nrv,2) % 2D- dimensional vector
> > How I can built a matrix z (3x2) avoiding loops as:
> >  x(1,:)-a(1,:)      x(1,:)-a(2,:)
> >  x(2,:)-a(1,:)      x(2,:)-a(2,:)
> >  x(3,:)-a(1,:)      x(3,:)-a(2,:)
> 
> one of the solutions
> - this is NOT pure vectorization...
> - it simply puts the loop into a stock function...
> 
>      nrp=3;
>      nrv=2;
>      v1=ceil(10*rand(nrp,2));
>      v2=ceil(5*rand(nrv,2));
>      [ix2,ix1]=meshgrid(1:nrv,1:nrp);
>      r=arrayfun(@(x,y) v1(x,:)-v2(y,:),ix1,ix2,'uni',false);
> % check
>     r
>      v1(3,:)-v2(2,:)
>      r{3,2}
> %{
> % r =
>      [1x2 double]    [1x2 double]
>      [1x2 double]    [1x2 double]
>      [1x2 double]    [1x2 double]
> % note: res based on random data!
>      2 -2
>      2 -2
> %}
> 
> us


It works well, but I would like to get a definitelly matrix z avoiding loops:

I think, one way to do it, for example the first two columns:

        x(1,:)-a(1,:)      x(1,:)-a(2,:)
        x(2,:)-a(1,:)      x(2,:)-a(2,:)
        x(3,:)-a(1,:)      x(3,:)-a(2,:)


can be described with: 

x-repmat(a(1,:),nrp,1) % first column

x-repmat(a(2,:),nrp,1) % second column

But, how I can built a z matrix with N columns?

I would like to write down these two columns in a more general form to N columns.

Some idea?
Thanks in advance.

Jose.