Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analogue of unique function that keeps order and repetition (MATLAB)

Tags:

matlab

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

But as you see, I'm missing the 'one' in the end. So, I tried to write a loop, but is in not doing what I though it should do. I was expecting it to delete one of the repeated values, and looping should have ensured that only one value remained. However, the output is:
x=[3,3,1,1,2,1,1]
The loop:
for i=1:length(x)
if x(i)==x(i+1)
x(i)=[];
end;
end;
Is there a way to generate output as in y? Where is the mistake in my loop?

like image 868
user3349993 Avatar asked Sep 02 '14 15:09

user3349993


Video Answer


2 Answers

If you would prefer a no-loop approach -

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

Or

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

Or

y = x([1 diff(x)]~=0)
like image 195
Divakar Avatar answered Nov 15 '22 02:11

Divakar


Ask your question also asks, where the mistake in your code is, here comes the answer to that. Here comes variation of your code, which 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;
  1. In your loop i runs from 1 to length(x). In the last iteration there is no i+1 element left, as i already is equal to length(x).
  2. When deleting elements of vectors in a loop, it is a common technique to loop from the end till the beginning, not from the beginning to the end. Then your code works just fine.
like image 29
Nras Avatar answered Nov 15 '22 01:11

Nras