Accumarray如何设置“有趣”只使用每个bin的最后一个obs

时间:2014-02-24 15:56:17

标签: matlab accumarray

有没有办法让accumarray放弃每个观察但是每个观察组的最后一个?

我的想法是类似的东西:

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

举个例子,假设我有以下内容:

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

我实际上只考虑accumarray,因为我只是用它来计算每个bin的观察值的平均值。所以每个可以制作技巧的功能对我来说都没问题。

2 个答案:

答案 0 :(得分:4)

当然,您可以使用accumarray执行此操作。 x(end)是数组中的最后一个观察。请注意,bin需要进行排序才能使其正常工作,因此如果不是,请运行 [bin,sortIdx]=sort(bin);x = x(sortIdx);首先。

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

答案 1 :(得分:2)

您已经得到了accumarray答案,但由于您正在寻找可以完成此任务的任何解决方案,请考虑unique的以下应用。

unique'legacy'选项一起使用,可根据需要为每个值的 last 出现索引:

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

现在,我 accumarray,正如许多人所知,但我实际上更喜欢这个解决方案。

相关问题