Analogue to a unique function that preserves order and repetition (MATLAB)

Suppose I have data: x = [3,3,1,1,1,2,2,1,1,1,1]
I would like to have a way out:
y = [3,1,2,1]
With a unique function () I could get:
z = [3,1,2]

But, as you can see, in the end I missed the "one." So, I tried to write a loop, but I am not doing what I have to do. I expected it to remove one of the duplicate values, and the loop should ensure that only one value remains. However, the output is:
x = [3,3,1,1,2,1,1]
Cycle:
for i=1:length(x)
if x(i)==x(i+1)
x(i)=[];
end;
end;
Is there a way to generate output like in y? Where is the error in my loop?

+6
source share
2 answers

If you prefer a loopless approach -

 y = x([1 diff(x)~=0]==1) 

or

 y = x([1 abs(diff(x))]>0) 

or

 y = x([1 diff(x)]~=0) 
+5
source

Ask your question and ask where the error is in your code, here is the answer to this question. Here's a variation of your code that works:

 x = [3,3,1,1,1,2,2,1,1,1,1]; for i=length(x):-1:2 if x(i)==x(i-1) x(i)=[]; end; end; 
  • In your loop, i runs from 1 to length(x) . There is no i+1 element in the last iteration, since i already equal to length(x) .
  • When removing elements of vectors in a cycle, the generally accepted technique is to cycle from end to beginning, and not from beginning to end. Then your code works fine.
+2
source

Source: https://habr.com/ru/post/974699/


All Articles