Star
Star

Reputation: 2299

Using hist in Matlab to compute occurrences

I am using hist to compute the number of occurrences of values in a matrix in Matlab.

I think I am using it wrong because it gives me completely weird results. Could you help me to understand what is going on?

When I run this piece of code I get countsB as desired

rng default; 
B=randi([0,3],10,1);
idxB=unique(B);
countsB=(hist(B,idxB))';

i.e.

B=[3;3;0;3;2;0;1;2;3;3];
idxB=[0;1;2;3];
countsB=[2;1;2;5];

When I run this other piece of code I get wrong results for countsA

A=ones(524288,1)*3418;
idxA=unique(A);
countsA=(hist(A,idxA))';

i.e.

idxA=3148;
countsA=[zeros(1709,1); 524288; zeros(1708,1)];

What am I doing wrong?

Upvotes: 2

Views: 57

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112689

To add to the other answers: you can replace hist by the explicit sum:

idxA = unique(A);
countsA = sum(bsxfun(@eq, A(:), idxA(:).'), 1);

Upvotes: 3

HelloWorld
HelloWorld

Reputation: 725

I think it has to do with:

N = HIST(Y,M), where M is a scalar, uses M bins.

and I think you are assuming it would do:

N = HIST(Y,X), where X is a vector, returns the distribution of Y
among bins with centers specified by X.

In other words, in the first case matlab is assuming that you are asking for 3418 bins

Upvotes: 2

Yuval Harpaz
Yuval Harpaz

Reputation: 1426

idxA is a scalar, which means the number of bins in this context. setting idxA as a vector instead e.g. [0,3418] will get you a hist with bins centered at 0 and 3418, similarly to what you got with idxB, which was also a vector

Upvotes: 3

Related Questions