I want to efficiently count the number of occurences of numbers between 1-numel(num) in a Matrix. I came up with two options for that:
sz = [3000 2000];mx = prod(sz);num = randi([1 mx],sz);tic;% First option
counts = zeros(numel(num),1);for i = 1:numel(num) counts(num(i)) = counts(num(i)) + 1;endtoctic;% Second option
uni = unique(num);uni = reshape(uni,[],1);hc = histcounts(num,[uni;uni(end)]);toc
Execution times are:
Elapsed time is 0.098540 seconds.Elapsed time is 0.342214 seconds.
So option 1 is clearly faster. However the for loop bugs me. Is there any possibility to vectorize this?
Best Answer