Counting frequency of occurrence in matrix

조회 수: 130 (최근 30일)
Guan Zhao
Guan Zhao 2012년 10월 23일
댓글: Brian Derstine 2021년 8월 31일
Good day,
I am attempting to count the number of times each number in a matrix occurred in the matrix.
For example, suppose I have a matrix;
x =
22 23 24 23
24 23 24 22
22 23 23 23
I want an output which will tell me 22 occurred 3 times, 23 occurred 6 times, and 24 occurred 2 times. The actual matrix is larger in size.
Is there a specific function which returns such values or are there any other ways I can resolve this challenge?
  댓글 수: 3
Jerry Olup
Jerry Olup 2017년 6월 20일
Let x be your vector. Something like this can save you an unnecessary toolbox:
xx = unique(x); % temp vector of vals
x = sort(x); % sorted input aligns with temp (lowest to highest)
t = zeros(size(xx)); % vector for freqs
% frequency for each value
for i = 1:length(xx)
t(i) = sum(x == xx(i));
end
Then the t vector shows freqs of the sorted, unique vector x.
m_vdv
m_vdv 2018년 5월 10일
Hi, is it also possible to do this without using 'unique' and 'sort'? For example with only using a for loop and/or if loop? Thanks in advance.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 10월 23일
x =[
22 23 24 23
24 23 24 22
22 23 23 23];
a = unique(x);
out = [a,histc(x(:),a)];
  댓글 수: 8
Lavanya T
Lavanya T 2021년 8월 17일
Thank you
Brian Derstine
Brian Derstine 2021년 8월 31일
would be nice if you could just do tabulate(x)

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

추가 답변 (3개)

Aurelien Queffurust
Aurelien Queffurust 2012년 10월 23일
Using nnz for example:
nnz(x==22)
will return 3
  댓글 수: 1
Guan Zhao
Guan Zhao 2012년 10월 23일
Hi,
My actual matrix will have at least 256 elements. I will have to consider zero elements too.
Regards
Guan Zhao

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


Thomas
Thomas 2012년 10월 23일
x=[22 23 24 23
24 23 24 22
22 23 23 23];
[a,b]=hist(x,unique(x));
out=[b' sum((a),2)]

abdelrahim hashem
abdelrahim hashem 2017년 11월 15일
x = [22 23 24 23; 24 23 24 22; 22 23 23 23];
un_x = unique(x);
for i = 1:length(un)
un(i), length(find(x == un_x(i)))
end

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by