필터 지우기
필터 지우기

How to find number of values which are repeating in a column?

조회 수: 2 (최근 30일)
Yasir Ali
Yasir Ali 2017년 2월 16일
댓글: Walter Roberson 2017년 12월 28일
Hi, I have matrix of 4535 x 23. In first column I have id's which are repeating. I would like to know that how many times a specific id is repeating in first column of matrix. For example: visually I can see 75 is repeating 3 three times so I want output in a matrix which should be like matrix having first column as id and second column corresponding number repetition of values. (like: 75, 3). I tried histogram but unable to receive required information. Could you please help in wiring script?

답변 (1개)

Peter O
Peter O 2017년 2월 16일
Take a look at the histcounts function: [N,edges] = histcounts(X,edges) sorts X into bins with the bin edges specified by the vector, edges. The value X(i) is in the kth bin if edges(k) ≤ X(i) < edges(k+1). The last bin also includes the right bin edge, so that it contains X(i) if edges(end-1) ≤ X(i) ≤ edges(end).
So then:
X = A(:,1);
Vals = unique(X); % Already sorted for you!
[N, HighEdge] = histcounts(X, [Vals+0.5]);
Assuming your IDs are all integers this spits them into the bin underneath. Alternatively you can do something like
Edges = [(min(Vals)-1):1:max(Vals)] + 0.5;
to get counts for each ID.
  댓글 수: 3
Peter O
Peter O 2017년 2월 16일
Yes, looking back that solution was a little hasty. Sorry about that. Try this instead. Again, it's assuming your input is all integers.
Vals = unique(X);
V2 = [Vals(1)-0.5, Vals+0.5];
N = histcounts(X,V2);
C = [Vals' N'];
C will have the ID's in columm #1 and the repeat counts in Column #2.
Here's a test case input:
X = [233 11 18 91 01 91 18 17 10002 -43];
and expected output:
C =
-43 1
1 1
11 1
17 1
18 2
91 2
233 1
10002 1
Peter O
Peter O 2017년 2월 16일
And for completeness, you can also use unique by itself, in a two-liner. This variant handles cases where you're looking for total counts and your input doesn't have to be stricly integer. IMO, it's the more elegant way:
[Vals,~,ic] = unique(X);
N = arrayfun(@(x) sum(ic==x),1:max(ic));
C = [Vals', N'];

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by