Domanda

Is there a way to let accumarray drop every observation but the last of each group?

What I had in mind was something similar:

lastobs=accumarray(bin,x,[],@(x){pick the observation with the max index in each group};  

To give you an example, suppose I have the following:

bin=[1 2 3  3 3 4 4];  %#The bin where the observations should be put
x= [21 3 12 5 6 8 31]; %#The vector of observations
%#The output I would like is as follow  
lastobs=[21 3 6 31];  

I am actually thinking of accumarray only because I just used it to compute the mean of the observations for each bin. So every function that could make the trick would be fine for me.

È stato utile?

Soluzione

Of course you can do this with accumarray. x(end) is the last observation in an array. Note that bin needs to be sorted for this to work, so if it isn't, run [bin,sortIdx]=sort(bin);x = x(sortIdx); first.

lastobs = accumarray(bin(:),x(:),[],@(x)x(end)); %# bin, x, should be n-by-1

Altri suggerimenti

You already got your accumarray answer, but since you are looking for any solution that will do the job, consider the following application of unique.

Using unique with the 'legacy' option gives the index of the last occurrence of each value, as you need:

>> [~,ia] = unique(bin,'legacy')
ia =
     1     2     5     7
>> lastobs = x(ia)
lastobs =
    21     3     6    31

Now, I love accumarray, as many here are aware, but I actually prefer this solution.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top