Excluding one vector from another vector with repetition

조회 수: 7 (최근 30일)
Sarah Ansari
Sarah Ansari 2018년 6월 18일
댓글: Bruno Luong 2020년 12월 9일
I want to get a new vector that has elements of S excluding the values in C with repetition.
S=[1 3 0 2 0 0] C=[0 2] B=setdiff(S,C) B=[1 3] while I need the output as [1 3 0 0]. I need the other zeros in the output but setdiff removes all the zeros. I also tried ismember function and it has the same result.
B=S(~ismember(S,C)) B=[1 3]
To make it clearer, I need to exclude a from s with repetition while keeping the same order of elements in s.

채택된 답변

Paolo
Paolo 2018년 6월 18일
S=[1 3 0 2 0 0];
C=[0 2];
[~,col] = ismember(C,S);
S(col) = [];
S =
1 3 0 0
  댓글 수: 7
Jan
Jan 2020년 12월 9일
Please open a new thread, because this is a different question. Include some examples, which clarify uniquely, which outputs are wanted for which input.
Bruno Luong
Bruno Luong 2020년 12월 9일
Paolo's solution breaks if C contains elements not in S.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Bruno Luong
Bruno Luong 2020년 12월 9일
편집: Bruno Luong 2020년 12월 9일
From Alexander Gallard above comment (I agree he should open a new thread)
"This method didn't work for me if my C was, say, [0,0,2]
If I want to remove two zeros this wasn't quite cutting it.'
A=[3 1 0 2 0 0 4];
B=[0 7 0 2];
D = DiffRep(A,B)
function D=DiffRep(A,B)
D=A(~ismember(count(A),count(B),'rows'));
end
function C=count(A)
A=A(:);
[C,i]=sort(A);
j=find([true;diff(C)]);
lgt=diff(j);
c=ones(size(A));
c(j(2:end))=1-lgt;
c=cumsum(c);
c(i)=c;
C=[A,c];
end
gives result
A =
3 1 0 2 0 0 4
B =
0 7 0 2
D =
3 1 0 4

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by