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?
  4 个评论
Torsten
Torsten 2022-11-9
编辑:Torsten 2022-11-9
rng('default')
edges = 1:100;
data = randi(100,156,5);
count = arrayfun(@(i)nnz(data(:)==edges(i)),edges);
count
count = 1×100
4 7 4 10 9 9 6 5 10 10 12 8 8 9 9 6 9 11 11 12 7 3 8 8 7 9 12 5 7 9
sum(count)
ans = 780
156*5
ans = 780

请先登录,再进行评论。

回答(2 个)

Steven Lord
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)]
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
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by