user3240368
user3240368

Reputation: 119

matlab - number of occurrences in matrix

I have (n x n) matrix in Matlab. For example(n=3):

A=[1,2,3; 4,5,6; 1,9,9]

And I want to count number of occurrences for first n numbers (and create matrix B). Output:

B=[2,1,1]

Thank you.

Upvotes: 0

Views: 265

Answers (4)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

This can be done with ismember:

[lia,lib]=ismember(A,A(1,:))
h=hist(lib(lib>0),1:size(A,2))

Upvotes: 0

carandraug
carandraug

Reputation: 13081

This can be done very elegantly with bsxfun and sum.

sum (bsxfun (@eq, A(1:n), A(:)))

However, I believe your example is incorrect. In your example matrix

A=[1,2,3; 4,5,6; 1,9,9]

the first 3 elements are not [1 2 3] but [1 4 1] since in Matlab elements are in Column-major order. If you want to check the first n elements from the first row, then you should instead do:

sum (bsxfun (@eq, A(1,1:n), A(:)))

Upvotes: 1

ewz
ewz

Reputation: 423

This should do the trick:

  A=[1,2,3; 4,5,6; 1,9,9];

  for i=1:length(A)

      B(i) = length(find(A(1,i) ==A));   
  end

Upvotes: 0

marsei
marsei

Reputation: 7751

If you have the stat toolbox, you can use tabulate (doc), otherwise countmember (matlab exchange) will do it.

TABLE = tabulate(A(:));

Upvotes: 0

Related Questions