Unique values for each sequence

8 次查看(过去 30 天)
Hi,
I want to find the unique values for each sequence. For example, consider the vector:
x = [1 1 1 1 2 2 1 1 1 3 3 3 2];
The output (unique values) should be:
y = [1 2 1 3 2];
How can I achieve this?

采纳的回答

Image Analyst
Image Analyst 2021-9-26
Here's one way:
x = [1 1 1 1 2 2 1 1 1 3 3 3 2]
dx = [1, diff(x)]
x2 = x(dx ~= 0)
x2 is your output variable that you wanted.
x =
1 1 1 1 2 2 1 1 1 3 3 3 2
dx =
1 0 0 0 1 0 -1 0 0 2 0 0 -1
x2 =
1 2 1 3 2

更多回答(1 个)

John D'Errico
John D'Errico 2021-9-26
编辑:John D'Errico 2021-9-26
Hint: What does diff give you? TRY IT!
x = [1 1 1 1 2 2 1 1 1 3 3 3 2];
diff(x)
ans = 1×12
0 0 0 1 0 -1 0 0 2 0 0 -1
What would happen if we tried find on that result? TRY IT!
find(diff(x))
ans = 1×4
4 6 9 12
This almost seems to work, but it does not find the first element. And, the index for that find was off by 1. Hmm. So now try this tweak.
x(find(diff([x(1) - 1,x])))
ans = 1×5
1 2 1 3 2
As you can see, I created a new vector, where I insured that it will always find the first element in the vector.
Could you have figured this out yourself? Well, yes. One thing to remember is the function diff returns zero, when two consecutive elements are the same. So diffi is a great tool to try when you are looking for when something CHANGES.
Next, how do you find when something has changed in that sequence? Find will do that for you, becauuse find locates non-zero elements.
After that, you just need to figure out how to get them both to work together, to find exactly the elements you want.
If you don't see how this works, take it apart, starting in the middle, then work out.
  2 个评论
Ariane Moura
Ariane Moura 2021-9-26
Thanks for your explanation!!!!
Image Analyst
Image Analyst 2021-9-26
Please "Vote" for John's answer. Although it's essentially the same as mine, he went to the extra trouble to give you a thorough explanation and he deserves "reputation points" for that (which you can give by voting for it).

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by