计算数组中的重复整数

编程入门 行业动态 更新时间:2024-10-21 14:18:22
本文介绍了计算数组中的重复整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有这个向量:

x = [1 1 1 1 1 2 2 2 3 4 4 6 6 6 6]

我想根据自己的位置获取每个唯一编号的位置.

I would like to get the position of each unique number according to itself.

y = [1 2 3 4 5 1 2 3 1 1 2 1 2 3 4]

目前我正在使用:

y = sum(triu(x==x.')) % MATLAB 2016b and above

它很紧凑,但内存效率显然不高.

It's compact but obviously not memory efficient.

为了使MATLAB编程具有纯粹的美感,我将避免使用循环.您是否有更好的简单实现?

For the pure beauty of MATLAB programming I would avoid using a loop. Do you have a better simple implementation ?

上下文:

我的最终目标是对向量x进行排序,但受到一个约束,即出现次数N的数字要优先于出现次数超过N的另一个数字:

My final goal is to sort the vector x but with the constraint that a number that appear N times has the priority over another number that has appeared more than N times:

[~,ind] = sort(y); x_relative_sort = x(ind); % x_relative_sort = 1 2 3 4 6 1 2 4 6 1 2 6 1 6 1

推荐答案

假定x已排序,这是使用 unique , diff 和 cumsum :

Assuming x is sorted, here's one vectorized alternative using unique, diff, and cumsum:

[~, index] = unique(x); y = ones(size(x)); y(index(2:end)) = y(index(2:end))-diff(index).'; y = cumsum(y);

现在您可以应用最终排序:

And now you can apply your final sorting:

>> [~, ind] = sort(y); >> x_relative_sort = x(ind) x_relative_sort = 1 2 3 4 6 1 2 4 6 1 2 6 1 6 1

更多推荐

计算数组中的重复整数

本文发布于:2023-11-22 13:50:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617680.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   组中

发布评论

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

>www.elefans.com

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