例如,我有排序后的向量: [9 9 9 10 13 13 14 15 ] 我想给每个元素它的顺序(并保留相同的元素)。 即我想要的答案是: [1 1 1 2 3 3 4 5]
有什么想法吗? 谢谢!
注意:我的真实向量要大得多(大约 50,000 个元素),因此我无法手动完成...
最佳答案
利用输入数据的排序性质,这是一种使用 cumsum
和 diff
的方法 -
cumsum([logical(1) diff(a)~=0])
运行时测试 -
>> a = sort(randi([10,10000],[1,10000000]));% Input array
>> tic,[~,~,idx] = unique(a);toc % @rahnema1's soln with unique
Elapsed time is 0.883363 seconds.
>> tic,cumsum([logical(1) diff(a)~=0]);toc
Elapsed time is 0.074566 seconds.
关于matlab - 如何给出向量中每个元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40282195/