big = 10000000;
maxValue = 350;
numBins = 20;
binEdges = linspace(0,maxValue,numBins+1);

x = maxValue*rand(big,1);


%% Original non-optimized code
tic
count = nan(numBins,1);
for binNum = 1:numBins
    isToRight = find(x > binEdges(binNum));
    isToLeft  = find(x > binEdges(binNum+1));
    isInBoth  = intersect(isToRight, isToLeft);
    count(binNum) = numel(isInBoth);
end
toc
%% Optimized code using direct logical indexing (9x faster)
tic
count = nan(numBins,1);
for  binNum = 1:numBins
 isToRight = (x > binEdges(binNum));
 isToLeft  = (x > binEdges(binNum+1));
 isInBoth  = (isToRight & isToLeft);
 count(binNum) = sum(isInBoth); % or: nnz(isInBoth)

end
toc
