Unique values for each sequence

2 views (last 30 days)
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?

Accepted Answer

Image Analyst
Image Analyst on 26 Sep 2021
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

More Answers (1)

John D'Errico
John D'Errico on 26 Sep 2021
Edited: John D'Errico on 26 Sep 2021
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 Comments
Ariane Moura
Ariane Moura on 26 Sep 2021
Thanks for your explanation!!!!
Image Analyst
Image Analyst on 26 Sep 2021
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).

Sign in to comment.

Categories

Find more on Historical Contests in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!