1

I want to count the number of values in the array. I have a code which works:

Range = [1:10^3];% [1:10^6];
N = 10^2;% 10^8

Data = randi([Range(1),Range(end)],N,1);

Counts = nan(numel(Range),1);

for iRange = 1:numel(Range)
   Counts(iRange) = sum(Data==Range(iRange)); 
end

Could you help me to make this code faster?

I feel that it should be via unique or hist, but I could not find a solution.

N = histcounts(Data,Range)

gives me 999 numbers instead of 1000.

3
  • 4
    hist or even better histcounts should do the job. Have you tried them? Commented Jul 24, 2018 at 8:43
  • I know that they should do a job, but I could not find the way. Commented Jul 24, 2018 at 9:10
  • The second argument of histcounts, as the documentation states, are the edges of the bins. [0,1,2] will return 2 values: the count of the numbers between 0-1 and the ones between 1-2. Just define your range properly. Perhaps 0:10^3? Commented Jul 24, 2018 at 9:17

2 Answers 2

1

As Ander Biguri stated at a comment, histcounts is what you seek.

The function counts the number of values of X (Data in your example), are found at every bin between two edges, where bins defined as such:

The value X(i) is in the kth bin if edges(k) ≤ X(i) < edges(k+1).

While the last bin also includes the right edges.

This means:

  1. For N values, you need N+1 edges.
  2. Each bin should start at the value you want it to include (1 between 1:2, 2 between 2:3, etc).

In your example:

Counts = histcounts(Data,Range(1):(Range(end)+1))';

Sign up to request clarification or add additional context in comments.

Comments

0

I wanted to point out an issue with this code:

Counts = nan(numel(Range),1);
for iRange = 1:numel(Range)
   Counts(iRange) = sum(Data==Range(iRange)); 
end

It shows a single loop, but == and sum work over all elements in the array, making this really expensive compared to a loop that doesn't do so, especially if N is large:

Counts = zeros(numel(Range),1);
for elem = Data(:).'
   Counts(elem) = Counts(elem) + 1;
end

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.