help-octave
[Top][All Lists]

## Re: vectorization

 From: Paul Kienzle Subject: Re: vectorization Date: Fri, 6 Dec 2002 09:46:01 -0500 User-agent: Mutt/1.2.5.1i

```On Fri, Dec 06, 2002 at 10:50:35AM +0100, Francesco Potorti` wrote:
> >In some work I'm now doing, I continually find the need to determine the
> >set of indices of vector A which contain elements of vector B - elements of
> >B will occur in A no more than once.  Here's an example of what my code
> >looks like:
> >
> ># contrived example
> ># vector A
> >i_num = [1:100];
> ># vector B
> >v_num = [ 1 3 5 12 ];
> >
> >lt = length(v_num);
> >
> >for i = 1:lt
> >
> >  idx(i) = find( i_num == v_num(i) );
> >
> >endfor;
> >
> >In this example, idx would of course be 1,3,5,12.  So it's sort of a
> >two-dimensional "find".  I'll just bet I'm doing this the hard way.  Is
> >there another way without a for-loop?  For the cases I'm seriously
> >concerned with, the vectors contain 5,000 to 15,000 elements.
>
> I tried to do it in two dimensions, by building ad hoc matrices and
> comparing them.  This way, I hoped to trade memory space for cpu cycles.
> Unfortunately my way is twice as slow as yours.  Maybe on a different
> architecture this will change, or maybe someone will have a better idea
> looking at my example:
>
> octave2.1> v=[504030,1566234,181111,32383]; n=[0:1500000]';
> octave2.1> tic; for i=1:length(v); idx(i)=find(n==v(i)); endfor; sort(idx)',
> toc
> ans =
>
>    11112   32384  181112  504031
>
> ans = 3.5039
> octave2.1> tic; find(sum((ones(size(n))*v==n*ones(size(v)))')), toc
> ans =
>
>    32384  181112  504031
>
> ans = 7.3894

If n contains valid indices, you could also be able to do it with sparse:

n=[2:2:150000];
v=[4:16:100000];
tic; sparse(1,n,[1:length(n)])(v), toc

ans = 0.32846

but it doesn't get you that much beyond the more general "lookup" solution:

tic; lookup(n,v); toc

ans = 0.42895

Paul Kienzle

>
> --
> Francesco PotortÃ¬ (researcher)         Voice: +39 050 315 3058 (op.2111)
> ISTI - Area della ricerca CNR          Fax:   +39 050 313 8091
> via G. Moruzzi 1, I-56124 Pisa         Email: address@hidden
> Web: http://fly.cnuce.cnr.it/          Key:   fly.cnuce.cnr.it/public.key
>
>
>
> -------------------------------------------------------------
> Octave is freely available under the terms of the GNU GPL.
>
> Octave's home on the web:  http://www.octave.org
> How to fund new projects:  http://www.octave.org/funding.html
> Subscription information:  http://www.octave.org/archive.html
> -------------------------------------------------------------
>

-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------

```