Info

# delete same number every two number while keeping the original order

1 view (last 30 days)
Andy on 27 May 2014
Closed: MATLAB Answer Bot on 20 Aug 2021
I have one row data, I want the result only leep one number among every two same number. The function"unique" can not do this work. for example: the data i have is as follows:
A = [ 1,1,1,2,2,2,3,3,4,4,4,1,1,1,5,5,2,2,1,1,6]
I want to have the result like this:
A = [1,2,3,4,1,5,2,1,6]. In the result, same number is allowed, but same number every two number is not allowed.
Furthermore, this method is going to be applied to a matrix which have contains number and nan. i.e. B = [1,1,3,3,4,3,3,2,2,nan,nan,nan,nan; 2,3,3,4,4,2,2,nan,nan,nan,nan,nan,nan; 1,1,2,2,1,1,4,4,4,nan,nan,nan,nan]
the result i wish to get is
B = [1,3,4,3,2,nan,nan,nan,nan,nan,nan,nan,nan； 2,3,4,2，nan,nan,nan,nan,nan,nan,nan,nan,nan; 1,2,1,4,nan,nan,nan,nan,nan,nan,nan,nan,nan]
what kind of code can achieve this target? Many thanks!

Image Analyst on 27 May 2014
What about just using the brute force method. It's intuitive and fast:
A = [ 1,1,1,2,2,2,3,3,4,4,4,1,1,1,5,5,2,2,1,1,6]
Aout = A(1); % Initialize output row vector.
for k = 2 : length(A)
if A(k) ~= Aout(end)
Aout(end+1) = A(k); % It's a new/different value so add it on.
end
end
% Print Aout to command window:
Aout
Andy on 29 May 2014
Thank you very much!

rifat on 27 May 2014
Edited: rifat on 27 May 2014
a(end+1)=a(end)+1;
x=diff(a);
p=find(x~=0);
a=a(p)
Andy on 29 May 2014
Hi, to apply this code to matrix, i use this code, do u think if there could be any improvement so that the matlab will calculate faster? Thank you very much.
B(:,end+1) = B(end)+1; x =diff(B,1,2); C = []; for temp = 1:size(B,1); p =[]; p=find(x(temp,:)~=0); C(temp,1:length(p)) = B(temp,p); end
C(C ==0)=nan;

Andrei Bobrov on 29 May 2014
x = [true(size(B,1),1), diff(B,1,2)~=0]';
ii = sort(x,'descend');
Bt = B';
z = nan(size(x));
z(ii) = Bt(x);
out = z';