for loop to update frequency count
3 次查看(过去 30 天)
显示 更早的评论
i have a solution to my problem but it does not use a for loop and i think i can get a more complete answer with one. i have a decent sized matrix, lets say 500 x 500, containing values between 0 and 1000. i want to find the frequency that each value appears in my matrix and get back a 1001 X 2 matrix, column 1 are the values 0 through 1000 and the second column is the count. i know a very simple way to get the counts of the values that appear at least once, but i want to include the unused values as well. here is what i have:
function Y = test(X)
ux = unique(X);
x = [ux,histc(X(:),ux)];
a = [0:1:min(ux)-1]';
b = zeros(min(ux), 1);
n = horzcat(a,b);
F = vertcat(n,x);
Here is as far as i've gotten in my for loop:
num_rows = size(X,1)
num_cols = size(X,2)
% loop through all values
for i = 1 : 1 : num_rows
for j = 1 : 1 : num_cols
F(X(i,j) + 1,2) =
end
end
can anyone point me in the right direction?
2 个评论
Walter Roberson
2015-9-20
You have values between 0 and 1000 but you expect only 501 different values, not 1001. And you expect some of the values might be missing from X. In order to list the missing values, we need to know which 501 values to expect might be present and which are not expected to be present. For example do you expect only even numbers? Are all of the entries integers? What should be done if a value in X is not one of the 501 that you expect?
回答(2 个)
Leo Simon
2015-9-20
This gets close I think
A = floor(rand(500)*1001);B=A(:);I = find(B<501); [N,X] = hist(B(I),501);
X contains the centers of the 501 bins of the histogram.
So I think,
[ floor(X), N ]
seems to be what you need?
0 个评论
Walter Roberson
2015-9-21
count_matrix = accumarray(X(:)+1, 1, [1001 1]); %provided that the entries are integers
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!