help-octave
[Top][All Lists]

## Re: Applying function to vector by index

 From: Mike Miller Subject: Re: Applying function to vector by index Date: Mon, 9 Dec 2002 11:28:28 -0600 (CST)

```On Mon, 9 Dec 2002, Iago Mosqueira wrote:

> > How does the second vector specify the bins in the first vector?  Can you
> > give an example?
>
> If idx was to like this: [1 1 1 2 2 3 3 3 3 4 4], I would like to get
> var=[3.2 4.5 6.7 3.3], that is, four values, one for each bin.

I think I understand now.  You want to avoid loops, so you don't want
this:

n=4; vard=zeros(1,n);
for i=1:n, vard(i)=var(d(find(idx==i))); end

But that might not be so bad compared to some of your alternatives.

Mike

> To estimate the mean, I use to do
>
>     sparse(idx,idx,d,'sum')./sparse(idx,idx,d)
>
> but this needs too much memory for my present vectors, and only works for
> the mean.
>
> > > I want to estimate the variance, or any other function, of the values
> > > from the first vector for each of the categories described by the
> > > second, without using a loop. Is there any obvious way of doing this I
> > > am overlooking? In R one could do
> > >
> > >     sapply(split(d,idx),var)
> > >
> > > where d is my data vector and idx the index vector.
> >
> >
> > It depends on what is in 'idx'.  It could be something like this...
> >
> > var(d(idx))
> >
> > ...and it would be exactly that if the elements of idx specified the
> > elements of d for which the variance was to be computed.
> >
>
> Yes, but I would have to loop over all possible values in idx.
>
> Many thanks,
>
>
> iago

-------------------------------------------------------------
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
-------------------------------------------------------------

```