Search code examples
matlabaccumarray

Accumarray how to set "fun" to use only last obs of each bin


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.


Solution

  • 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