Lets say I have a matrix x=[ 1 2 1 2 1 2 1 2 3 4 5 ]. To look at its histogram, I can do h=hist(x).

Now, h with retrieve a matrix consisting only the number of occurrences and does not store the original value to which it occurred.

What I want is something like a function which takes a value from x and returns number of occurrences of it. Having said that, what one thing histeq does should we admire is, it automatically scales nearest values according!

How should solve this issue? How exactly people do it?

My reason of interest is in images:

Lets say I have an image. I want to find all number of occurrences of a chrominance value of image.


1 Answer 1

%Let's say:
X = [1 2 3 4 4 4 3 2 1 5 10];
Num = input("Please enter the number");
temp = X == Num;

%let's assume Num in this case is 4
%temp = [0 0 0 1 1 1 0 0 0 0 0]

ans = sum(temp);

ans = 3

This is a quick and an effective way to find the number of occurrences of a particular value.

  • $\begingroup$ That's simple on int. Consider you have all decimal values and given a number 12.335, it might not be in X but it might fit nearest to some number n: 12.00 which has frequency. how to fix it? $\endgroup$
    – 0cool
    Commented Mar 2, 2014 at 15:55
  • $\begingroup$ That would be the function round(). round(12.335) will be 12. You can then use the above code. Note: round(12.5) is 13 and not 12. $\endgroup$ Commented Mar 3, 2014 at 4:27
  • $\begingroup$ For non-integers I would use a range e.g. X>11.5 & X<=12.5. This can give you a bit more flexibility than rounding depending on what you are interested in. $\endgroup$
    – nivag
    Commented May 1, 2014 at 8:21
  • $\begingroup$ A similar alternative to your example is numel(X(X==4)); which gives the answer in a single line. $\endgroup$
    – nivag
    Commented May 1, 2014 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.