How can I count frequency in array?

I try to make a code which count the frequency of number in an array but the number output is incorrect. my coding:
clc; clear; element = zeros (1,50); ctr=1; i=1; freq=0;
num = input('Please state how many numbers you want to input: ');
while (ctr <= num) %input number in array
element (ctr) = input( 'Enter number: ');
ctr = ctr+1;
end
for ctr=1:1:num %to arrange number in descending
for i=1:1:num
if element (i) < element (i+1)
temp = element(i);
element (i) = element (i+1);
element (i+1) = temp;
end
end
end
disp('N Count');
for y=1:1:num %counting frequency of number
k = element(y);
if k ~= element (y+1)
for x = y:1:num
if k == element (x+1)
freq = freq+1;
end
end
fprintf('%d','%d',k, freq);
end
freq=0;
end
pause;
The output is as follow:
Please state how many numbers you want to input: 2 Enter number: 1 Enter number: 2 N Count 37100203710010

 Respuesta aceptada

George
George el 24 de Sept. de 2016
fprintf prints to a file. You want to use sprintf. Also, your formatSpec is wrong. You want to define it as one string. Something like:
str = sprintf('%d %d', k, freq);
disp(str)
Should work.

3 comentarios

George
George el 24 de Sept. de 2016
Also there are more MATLABy ways to do what you're trying to do. eg:
sum(nnz(A == 3))
will give you the sum of non-zero elements of the logical array A==3. This, effectively, tells you how many elements of A are equal to 3.
fizz gerbera
fizz gerbera el 24 de Sept. de 2016
Editada: fizz gerbera el 24 de Sept. de 2016
thanks george. it can print the answer fine now. i tried to your suggestion.my coding is as follows, but i cant seem to make it work.
while k<=num
sum(nnz(A == k));
fprint('%d', k);
k=k+1;
end
George
George el 24 de Sept. de 2016
You should not be using fprintf.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Preguntada:

el 24 de Sept. de 2016

Comentada:

el 24 de Sept. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by