Excluding one vector from another vector with repetition

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 日

2 投票

S=[1 3 0 2 0 0];
C=[0 2];
[~,col] = ismember(C,S);
S(col) = [];
S =
1 3 0 0

7 件のコメント

Sarah Ansari
Sarah Ansari 2018 年 6 月 18 日
Thank you for your quick and perfect answer.
Stephen23
Stephen23 2018 年 6 月 18 日
+1 that is really neat! Good idea, Paolo.
Paolo
Paolo 2018 年 6 月 18 日
Happy to help Sarah, and thank you Stephen :)
IBM watson
IBM watson 2018 年 10 月 23 日
Hi. I used your code in my algorithm and i got this:
boxes0: subscripts must be either integers 1 to (2^63)-1 or logicals
  • boxes is the main vector like your S.
Could you help me to fix this please?
Alexander Gallard
Alexander Gallard 2020 年 12 月 9 日
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. Any ideas?
Kind of an old thread but would love a pointer! (:
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 日

0 投票

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

カテゴリ

製品

リリース

R2016b

質問済み:

2018 年 6 月 18 日

コメント済み:

2020 年 12 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by