I want to count (tally) the number of occurrences of any generated integer over a 156 for-loop.
3 次查看(过去 30 天)
显示 更早的评论
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?
回答(2 个)
Steven Lord
2022-11-9
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)]
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.
0 个评论
Walter Roberson
2022-11-9
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!