Borrar filtros
Borrar filtros

Counting frequency of occurrence in matrix

59 visualizaciones (últimos 30 días)
Guan Zhao
Guan Zhao el 23 de Oct. de 2012
Comentada: Brian Derstine el 31 de Ag. de 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 comentarios
Jerry Olup
Jerry Olup el 20 de Jun. de 2017
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 el 10 de Mayo de 2018
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.

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 23 de Oct. de 2012
x =[
22 23 24 23
24 23 24 22
22 23 23 23];
a = unique(x);
out = [a,histc(x(:),a)];
  8 comentarios
Lavanya T
Lavanya T el 17 de Ag. de 2021
Thank you
Brian Derstine
Brian Derstine el 31 de Ag. de 2021
would be nice if you could just do tabulate(x)

Iniciar sesión para comentar.

Más respuestas (3)

Aurelien Queffurust
Aurelien Queffurust el 23 de Oct. de 2012
Using nnz for example:
nnz(x==22)
will return 3
  1 comentario
Guan Zhao
Guan Zhao el 23 de Oct. de 2012
Hi,
My actual matrix will have at least 256 elements. I will have to consider zero elements too.
Regards
Guan Zhao

Iniciar sesión para comentar.


Thomas
Thomas el 23 de Oct. de 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)]

abdelrahim hashem
abdelrahim hashem el 15 de Nov. de 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

Categorías

Más información sobre Sparse Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by