【问题标题】:Accumarray how to set "fun" to use only last obs of each binAccumarray 如何设置“有趣”以仅使用每个 bin 的最后一个 obs
【发布时间】:2014-02-24 15:56:16
【问题描述】:

有没有办法让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 的观察值的平均值。所以每一个能成功的函数对我来说都很好。

【问题讨论】:

    标签: matlab accumarray


    【解决方案1】:

    当然,您可以使用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
    

    【讨论】:

    • 谢谢乔纳斯,我仍然对索引一团糟。我尝试了很多组合,但不是最简单的组合!很高兴您总是在场为您提供帮助
    • 对于未来的读者:bin 需要排序才能正常工作!
    • @knedlsepp: 不,bin 可以是任意顺序,只要它的顺序与x 中元素的顺序相对应。或者你能举一个它不起作用的例子吗?
    • 对我来说:bin = repmat(1:10,1,2); accumarray(bin(:),1:length(bin),[],@(x)x(end)) 将输出11 12 13 14 5 6 7 18 19 20 而不是11:20。由于最近的question 和Luis 的回答,我确实写了一个简短的Q&Adoc accumarray 在 Input Arguments-fun 下列出了这种行为。很隐蔽……
    • @knedlsepp:嗯,TIL。编辑了我的答案。
    【解决方案2】:

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

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

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

    现在,我喜欢 accumarray,这里的很多人都知道,但我实际上更喜欢这个解决方案。

    【讨论】:

    • 感谢 chappjc,我对 matlab 还是很陌生,每个答案都是我可以学习的。无论如何,我明天将与最大的系列合作,我将检查两种解决方案,看看哪一个是最快的。再次感谢您的回答。
    • @Gio accumarray 在大多数情况下非常快,但也许使用这个特定的fun 可能会慢一些。
    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多