1

有没有办法让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因为我只是用它来计算每个箱的观察平均值。所以每一个能成功的功能对我来说都很好。

4

2 回答 2

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
于 2014-02-24T15:59:09.517 回答
2

您已经得到了accumarray答案,但是由于您正在寻找可以完成这项工作的任何解决方案,请考虑以下unique.

unique与选项一起使用会根据需要给出每个值最后一次'legacy'出现的索引:

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

现在,我喜欢 accumarray,正如这里的许多人都知道的那样,但我实际上更喜欢这种解决方案。

于 2014-02-24T18:37:55.560 回答