如何在一组分组变量中找到最后一个元素?

编程入门 行业动态 更新时间:2024-10-25 08:16:25
本文介绍了如何在一组分组变量中找到最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个150x2的矩阵,其中第一列包含可以视为分组变量"的数字,第二列包含与那些分组变量关联的值.因此,较小的12x2版本看起来像这样

I have a 150x2 matrix in which the first column contains numbers that can be considered 'grouping variables' and the second column contains values associated with those grouping variables. So a small 12x2 version would look like this

200741 5441 200741 5524 200741 5428 200742 5670 200742 5668 200742 5559 200742 5215 200743 5184 200743 5473 200743 5496 200743 5568 200743 5702

我想找到与每个分组变量关联的值的最后一个值.因此,上面的示例将生成最后一个元素5428(对于变量200741),最后一个元素5215(对于变量200742)& 5702的最后一个元素(用于将变量200743分组).在coumn1中找到分组变量的唯一值后,如何获取column2中与每个分组变量相对应的最后一个元素?在Matlab中怎么做?

I'd like to find the last value of the values associated with each grouping variable. So the above example would yield a last element of 5428(for variable 200741), last element of 5215(for variable 200742) & last element of 5702(for grouping variable 200743). After I find the unique vales of grouping variables in coumn1, how do I take the last element in column2 corresponding to each grouping variable? How could this be done in Matlab ?

推荐答案

如果第一列是排序,并且包含正整数,则可以使用 accumarray (可以稍微拉伸一下):

If the first column is sorted and contains positive integers, you could use accumarray (admittedly stretching it a little):

result = nonzeros(accumarray(A(:,1), A(:,2), [], @(x) x(end), 0, true));

注意:

  • 排序要求源自以下事实:根据文档,

如果subs中的下标未按照其线性索引进行排序,则accumarray在将数据传递给fun

If the subscripts in subs are not sorted with respect to their linear indices, then accumarray might not always preserve the order of the data in val when it passes them to fun

,因此@(x) x(end)不会总是给出 last 元素.

and so @(x) x(end) would not always give the last element.

更多推荐

如何在一组分组变量中找到最后一个元素?

本文发布于:2023-10-28 00:51:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   元素   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!