count frequency of each unique occurence in an Nx2 matrix

조회 수: 2 (최근 30일)
lmac456
lmac456 2017년 9월 7일
댓글: ZIJIAN HE 2018년 11월 17일
I have a data set where each point is described by two unique numbers (call it a and b), and I need to count the number of times each combination of these two numbers occurs. For example if I had 6 points that were described by
mat = [1 1 ; 1 3 ; 2 3; 2 1; 1 2; 1 3]
where a is the first column and b is the second column, I want to know how many times a specific combo occurs. I know I can get the count of one number in a column doing something like this:
sum(mat(:,1)==1)
sum(mat(:,2)==3)
which would return 4 and 3, respectively, but I want to count how many times the combo (1, 3) occurs, which would be 2 for this list.

채택된 답변

Jacob Ward
Jacob Ward 2017년 9월 7일
You could iteratively test each row for the combo you are looking for, adding 1 to the total each time a match is found, like so:
mat = [1 1; 1 3; 2 3; 2 1; 1 2; 1 3];
totalOccurences = 0;
for i = 1:length(mat(:,1))
if mat(i,:)==[1 3]
totalOccurences = totalOccurences+1;
end
end
At the end of this code, totalOccurences = 2, which is the result you wanted to get in your example.
  댓글 수: 2
lmac456
lmac456 2017년 9월 8일
Perfect, thank you!
yiwen yim
yiwen yim 2018년 3월 21일
@Jacob Ward
May i know the definition on how this part works?
for i = 1:length(mat(:,1))
thank you.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2017년 9월 7일
If these are always going to be integer values, use histcounts2.

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by