How do you find the mode of an array with ONLY ceil() floor() rand() and length() functions.

I am trying to find the mode of a random array without ANY built in Matlab functions other than ceil(), floor(), length(), and rand() and have been unable to find a sufficient way.
My code was as follows: (Could anyone give some pointers?)
for j = 1:(length(array))
index = array(j)
for i = 2:(length(array)-1)
if (array(i) == index)
count = count + 1;
end
end
if total < count
total = count;
my_mode = index;
end
count = 0;
end
disp(my_mode)

Answers (1)

Here is a suggestion. I fail to see how ceil, floor and rand could be useful, except for creating some random data.
% create some data
A = ceil(4*rand(1,10))
% engine
N = length(A) ;
clear B ; B(1:N) = 1 ; % you cannot use ones, so use this trick for pre-allocation
for i1=1:N
for i2 = i1+1:N
if A(i2) == A(i1)
B(i1) = B(i1) + 1 ;
end
end
end
modeN = 0 ;
modeValue = NaN ;
for k=1:N, % replacement of max
if B(k) > modeN,
modeN = B(k) ;
modeValue = A(k) ;
end
end
disp(' Mode N ')
disp([modeValue modeN]) ;

1 Comment

It's not necessary to use those functions, those are just the only ones that are permitted to be used in this review. Are there any easier ways to find mode without incorporating those functions?

Sign in to comment.

Categories

Tags

Asked:

on 10 Dec 2013

Commented:

on 10 Dec 2013

Community Treasure Hunt

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

Start Hunting!