# Counting frequency of occurrence in matrix

362 views (last 30 days)

Show older comments

Guan Zhao
on 23 Oct 2012

Commented: Brian Derstine
on 31 Aug 2021

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 Comments

m_vdv
on 10 May 2018

### Accepted Answer

Andrei Bobrov
on 23 Oct 2012

x =[

22 23 24 23

24 23 24 22

22 23 23 23];

a = unique(x);

out = [a,histc(x(:),a)];

##### 8 Comments

### More Answers (3)

Thomas
on 23 Oct 2012

x=[22 23 24 23

24 23 24 22

22 23 23 23];

[a,b]=hist(x,unique(x));

out=[b' sum((a),2)]

##### 0 Comments

abdelrahim hashem
on 15 Nov 2017

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

##### 0 Comments

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!