Unique values for each sequence

6 ビュー (過去 30 日間)
Ariane Moura
Ariane Moura 2021 年 9 月 26 日
コメント済み: Image Analyst 2021 年 9 月 26 日
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 件のコメント
Ariane Moura
Ariane Moura 2021 年 9 月 26 日
Thanks!!!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeHistorical Contests についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by