Delete the same numbers appeared in different rows

1 view (last 30 days)
Hello everyone,
I'm construct the various row vector with different numbers
Suppose i have the several row as shown below
a = [5 14 9 6 7 8]
b = [1 10 6 2 3 4]
c = [14 23 18 15 16 17]
d = [10 19 15 11 12 13]
e = [23 32 27 24 25 26]
f = [19 28 24 20 21 22]
g = [32 38 36 33 34 35]
h = [28 37 33 29 30 31]
In row [a] and [b], I have the number 6 appeared both of this rows. Then row [b] and [d] have number 10 appeared and so on.
Do we have any procedure to find(or check) the same number that appeared twice in all rows.
I want to get the result of duplicated numbers as
ans = [6 10 14 15 19 23 24 28 32 33]
Any suggestion are appreciated
Thanks in advances

Accepted Answer

Jan
Jan on 5 Feb 2022
Edited: Jan on 5 Feb 2022
Are the rows unique? If so, just join all rows to one vector:
X = [5 14 9 6 7 8; ...
1 10 6 2 3 4; ...
14 23 18 15 16 17; ...
10 19 15 11 12 13; ...
23 32 27 24 25 26; ...
19 28 24 20 21 22; ...
32 38 36 33 34 35; ...
28 37 33 29 30 31];
uX = unique(X(:));
[N, Edge] = histcounts(X(:), [uX; uX(end) + 1]);
result = uX(N == 2)
% Or:
sX = sort(X(:));
q = [true; diff(sX) ~= 0];
N = diff([find(q); numel(sX) + 1]);
S = sX(q); % Unique values
result = S(N == 2) % Appearing twice

More Answers (2)

Cris LaPierre
Cris LaPierre on 5 Feb 2022
I can't think of a direct way to do it, but you could use histcounts to determine how many of each number there are, and then extract only those that appear twice.
a = [5 14 9 6 7 8];
b = [1 10 6 2 3 4];
c = [14 23 18 15 16 17];
d = [10 19 15 11 12 13];
e = [23 32 27 24 25 26];
f = [19 28 24 20 21 22];
g = [32 38 36 33 34 35];
h = [28 37 33 29 30 31];
[cnt,bin] = histcounts([a b c d e f g h],0:40);
ans = bin(cnt==2)
ans = 1×10
6 10 14 15 19 23 24 28 32 33
You just need to make sure you define the bins to be the max value+1.

Voss
Voss on 5 Feb 2022
This will work (as long as any number repeated more than once in a single row should also be counted as a duplicate):
a = [5 14 9 6 7 8];
b = [1 10 6 2 3 4];
c = [14 23 18 15 16 17];
d = [10 19 15 11 12 13];
e = [23 32 27 24 25 26];
f = [19 28 24 20 21 22];
g = [32 38 36 33 34 35];
h = [28 37 33 29 30 31];
idx = sort([a b c d e f g h]);
answer = unique(idx([false diff(idx) == 0]))
answer = 1×10
6 10 14 15 19 23 24 28 32 33
(And it also treats any number that appears more than twice the same as if it appeared only twice, i.e., information about the number of times a duplicate occurs is not retained.)

Community Treasure Hunt

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

Start Hunting!