Info

此问题已关闭。 请重新打开它进行编辑或回答。

delete same number every two number while keeping the original order

1 次查看(过去 30 天)
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!

回答(3 个)

Image Analyst
Image Analyst 2014-5-27
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 2014-5-27
编辑:rifat 2014-5-27
a(end+1)=a(end)+1;
x=diff(a);
p=find(x~=0);
a=a(p)
  1 个评论
Andy
Andy 2014-5-29
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 2014-5-29
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