HXSP1947
HXSP1947

Reputation: 1351

Matlab: Is there a quicker way to count the number of occurrences of a value in a vector?

Thanks in advance for the help

I am using the following to count the number of occurrences of the value x in a vector v

count = sum(v == x);

Is there anyway that I can decrease the time to count these occurrences? Notice that v tends to be small; usually no more than 100 elements. However, this operation occurs tens of thousands of times in my code and seems to be by far the most time consuming operation when analyzing my code using the profiler. I've looked at the accumarray function but it appears that the approach I give above tends to be faster (at least the way I tried to use it).

Upvotes: 2

Views: 122

Answers (1)

blubbafett
blubbafett

Reputation: 168

Depending on the rest of your code and the type of data, one possible way to approach this is to subtract x from v and count zeros instead. E.g.,

v = rand(200,1);
v(121) = v(3); % add some duplicates of v(3)
v(189) = v(3); % add some duplicates of v(3)
x = v(3);
count = numlel(v)-nnz(v-x);

Subtracting costs CPU-time but you might benefit from it in the end. Since I don't have your data I've just made a small test. You can test on your actual data to see whether it's something for you or not.

N = 100000; 
for k = 1:1
    v = randn(200,1);
    vy = zeros(size(v));
    v(121) = v(3);
    v(189) = v(3);
    x = v(3);

    t1=tic;
    for j = 1:N
        count1 = sum(v(:)==x);
    end
    t1s=toc(t1)/N;
    t2=tic;
    for j = 1:N % time the cost of subtraction prior to nnz()
        vy=v-x;
        count2 = numel(v)-nnz(vy);
    end
    t2s=toc(t2)/N;
    t3=tic;
    for j = 1:N % time the cost of subtraction within nnz()
        count3 = numel(v)-nnz(v-x);
    end
    t3s=toc(t3)/N;
    [count1 count2 count3]
    [t1s t2s t3s]
end


ans =

     3     3     3


ans =

   1.0e-05 *

    0.1496    0.1048    0.1222

You can see John D'Errico's answer here about counting zeros.

Upvotes: 1

Related Questions