Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

delete same number every two number while keeping the original order

1 vue (au cours des 30 derniers jours)
Andy
Andy le 27 Mai 2014
Clôturé : MATLAB Answer Bot le 20 Août 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!

Réponses (3)

Image Analyst
Image Analyst le 27 Mai 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

rifat
rifat le 27 Mai 2014
Modifié(e) : rifat le 27 Mai 2014
a(end+1)=a(end)+1;
x=diff(a);
p=find(x~=0);
a=a(p)
  1 commentaire
Andy
Andy le 29 Mai 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
Andrei Bobrov le 29 Mai 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';

Community Treasure Hunt

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

Start Hunting!

Translated by