保持顺序和重复的独特功能的类似物(MATLAB) [英] Analogue of unique function that keeps order and repetition (MATLAB)
问题描述
假设我有数据:
x = [3,3,1,1,1,2,2,1,1,1,1]
我想要输出:
y = [3,1,2,1]
使用unique()函数,我可以获得:
z = [3,1,2]
Suppose I have data:
x = [3,3,1,1,1,2,2,1,1,1,1]
I would like to have the output:
y = [3,1,2,1]
With unique() function I could get:
z = [3,1,2]
但是,正如您所看到的,我最终错过了一个".
因此,我试图编写一个循环,但是虽然我应该做的事没有做.
我期望它删除重复的值之一,并且循环应该确保仅保留一个值.但是,输出为:
x = [3,3,1,1,2,1,1]
循环:
for i=1:length(x)
if x(i)==x(i+1)
x(i)=[];
end;
end;
有没有一种方法可以像y一样生成输出?我的循环中的错误在哪里?
But as you see, I'm missing the 'one' in the end.
So, I tried to write a loop, but is in not doing what I though it should do.
I was expecting it to delete one of the repeated values, and looping should have ensured that only one value remained. However, the output is:
x=[3,3,1,1,2,1,1]
The loop:
for i=1:length(x)
if x(i)==x(i+1)
x(i)=[];
end;
end;
Is there a way to generate output as in y? Where is the mistake in my loop?
推荐答案
如果您希望采用无循环方法-
If you would prefer a no-loop approach -
y = x([1 diff(x)~=0]==1)
或
y = x([1 abs(diff(x))]>0)
或
y = x([1 diff(x)]~=0)
这篇关于保持顺序和重复的独特功能的类似物(MATLAB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!