Remove array values with multiple occurances from "parent" array

How do you remove values in an array from a "master database" array? For example:
a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
b = [1, 1, 2, 4, 4, 4]
I would like to remove each occurance of each value in 'b' from 'a' to get:
c = 1, 2, 2, 3, 3, 3
setdiff(a, b) doesn't work because it removes all instances from 'a' including the repeating values (it even says no repetitions in the documentation):
c = 3
[~, col] = ismember(b, a)
a(col) = []
doesn't work because it only removes one instance of the numbers (the first index where it occured):
c = 1, 1, 2, 2, 3, 3, 3, 4, 4
Thanks for the help.

 採用された回答

David Hill
David Hill 2020 年 7 月 9 日
編集済み: David Hill 2020 年 7 月 9 日

0 投票

a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4];
b = [1, 1, 2, 4, 4, 4];
c = a;
for i=b
c(find(c==i,1))=[];
end

1 件のコメント

Joe I
Joe I 2020 年 7 月 9 日
編集済み: Joe I 2020 年 7 月 9 日
Awesome, thanks! Works great, scales up to my datasets with tens of thousands of values in each. Seems so obvious now after seeing it. Just be sure that each variable is a row vector.

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 7 月 10 日
編集済み: Bruno Luong 2020 年 7 月 10 日

0 投票

Test samples
a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
b = [1, 1, 2, 4, 4, 4]
Code
u = unique([a,b]);
n = length(u);
[~, ia] = ismember(a,u); na = accumarray(ia(:),1,[n 1]);
[~, ib] = ismember(b,u); nb = accumarray(ib(:),1,[n 1]);
c = repelem(u,max(na-nb,0))
Result
c =
1 2 2 3 3 3

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

質問済み:

2020 年 7 月 9 日

編集済み:

2020 年 7 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by