Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

delete same number every two number while keeping the original order

조회 수: 1 (최근 30일)
Andy
Andy 2014년 5월 27일
마감: MATLAB Answer Bot 2021년 8월 20일
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