# I want to count (tally) the number of occurrences of any generated integer over a 156 for-loop.

1 view (last 30 days)
Jeffrey Lewis on 9 Nov 2022
Answered: Walter Roberson on 9 Nov 2022
I want to run a iteration 156 times via a for-loop. It will randomly generate an array of 5 numbers between 1-100. I want to know how many time any number within the range occured over the 156 iteration for loop. How would I be able to accomplish this?
Bonus question: Is there a way to code how many integers appear together in any given array?
Perhaps there is an easier way to code this type of iteration?
David Hill on 9 Nov 2022
data = randi(100,1,156*5);
h=histc(data,1:100)
h = 1×100
8 7 4 17 9 12 9 5 5 9 6 11 8 9 7 8 8 6 8 10 12 7 6 7 5 4 8 8 6 8

Steven Lord on 9 Nov 2022
Are all these values integer values? If so consider using histcounts with the 'integers' BinMethod.
values = randi(100, [200, 5]);
[counts, edges] = histcounts(values, BinMethod='integers', BinLimits = [1 100]);
spotCheck = [counts(42), nnz(values == 42)]
spotCheck = 1×2
10 10
We can also display a histogram and plot the data from histcounts to check.
histogram(values, BinMethod='integers', BinLimits = [1 100]);
hold on
bincenters = (edges(1:end-1)+edges(2:end))./2;
plot(bincenters, counts, 'ro')
plot(42, counts(42), 'k+')
It's a little hard to see the black + in the small picture on Answers, but if you ran this code in MATLAB and zoomed in you'd see it more clearly.

Walter Roberson on 9 Nov 2022
integers appearing "together" is not clear. Since your generation is an ordered vector, does that mean that the integers must be immediately beside each other in sequence? Or does it mean that as long as they show up together in the same vector of 5 that you want it to be counted?
For example, [2 7 7 3 1] -- should that increment the counts for (2,7), (7,7), (7,3), (3,1) ? Or should it increment the counts for (2,7), (7,2), (7,7), (7,3), (3,7), (3,1), (1,3) ? Or (2,7), (7,2), (7,7), (7,3), (3,7), (3,1), (1,3) and another (7,7) as well? Or for (1,2), (1,3), (1,7), (2,3), (2,7), (7,7) ? Or for (1,2), (1,3), (1,7), (2,1), (2,3), (2,7), (3,1), (3,2), (3,7), (7,1), (7,2), (7,3), (7,7) ? Or for (1,2), (1,3), (1,7), (1,7), (2,1), (2,3), (2,7), (2,7), (3,1), (3,2), (3,7), (3,7), (7,1), (7,2), (7,3), (7,7), (7,7) ?
maxval = 100;
counts = zeros(maxval, 1);
paircounts = zeros(maxval, maxval);
for K = 1:156
n = randi([1 maxval], 5, 1);
counts = counts + accumarray(n, 1, [maxval 1]);
paircounts = paircounts + accumarray( [n(1:end-1), n(2:end)], 1, [maxval, maxval]);
end
bar(counts)
imagesc(paircounts); colorbar

### Categories

Find more on Logical in Help Center and File Exchange

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!