Unique values for each sequence

조회 수: 2 (최근 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개)

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에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by