for loop to update frequency count

조회 수: 3 (최근 30일)
april cave
april cave 2015년 9월 20일
답변: Walter Roberson 2015년 9월 21일
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
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?
april cave
april cave 2015년 9월 20일
sorry, your right is should be 1001. i dont know which values between 0 and 1000 are in the matrix. what i know is it is it is 500x500 and i need to know how many times each of the values appears. so, i need a 1001x2 matrix; col 1 is the value, col 2 is the count. even if the only value that appears in the matrix is 5, i need to return a 1001x2 matrix with 0s in the second column in every row except row 6

댓글을 달려면 로그인하십시오.

답변 (2개)

Leo Simon
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?

Walter Roberson
Walter Roberson 2015년 9월 21일
count_matrix = accumarray(X(:)+1, 1, [1001 1]); %provided that the entries are integers

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by