Delete the same numbers appeared in different rows

조회 수: 2 (최근 30일)
Trang Hu Jia
Trang Hu Jia 2022년 2월 5일
댓글: Voss 2022년 2월 8일
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
  댓글 수: 1
Trang Hu Jia
Trang Hu Jia 2022년 2월 6일
Thank you very much for you suggestion
This help me a lot

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

추가 답변 (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.)
  댓글 수: 2
Trang Hu Jia
Trang Hu Jia 2022년 2월 6일
Thank you very much for you suggestion
Voss
Voss 2022년 2월 8일
You're welcome

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

카테고리

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