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?
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)
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;
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)
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With