I want to count (tally) the number of occurrences of any generated integer over a 156 for-loop.
조회 수: 12 (최근 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!


