我有一个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.
更多推荐
如何在一组分组变量中找到最后一个元素?
发布评论