Delete the same numbers appeared in different rows

2 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2022-2-5
编辑:Jan 2022-2-5
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

更多回答(2 个)

Cris LaPierre
Cris LaPierre 2022-2-5
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 2022-2-5
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.)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by