I' trying to find the mode of an input vector without using the built in mode function. I'm attempting to search said vector and add a count to a vector of zeros everytime it finds a certain number. Am i on the right track with this?

2 views (last 30 days)
function m = my_mode(vec)
sort(vec)
x=max(vec)
zvec=zeros(1,x)
for i=1:x
for i=vec(i)
zvec(i)=zvec(i)+1
end
end
m=find(zvec==max(zvec))

Answers (1)

Geoff Hayes
Geoff Hayes on 2 Dec 2015
William - are you assuming that your input vector has only positive integers (i.e. integers greater than zero)? If that is the case, then your idea to create an array of elements where each element corresponds to a count for that index (much like a histogram) and then determine which element has the maximum count, is fair.
I do have a couple of comments though: the output of sort is the sorted vector or array, so your call
sort(vec);
does the sorting but you are not capturing the sorted results. You would have to do instead
vec = sort(vec);
But is a sort really necessary? If we consider your for loops
for i=1:x
for i=vec(i)
zvec(i)=zvec(i)+1
end
end
your outer loop iterates from one to the maximum element in vec. But what is the purpose behind your inner for loop?
for i=vec(i)
You will have problems not only because you are re-using i for the inner loop (as an aside, you should avoid using i and j as indexing variable names since MATLAB also uses them to represent the imaginary number) which may conflict with the indexing variable of the outer for loop. But also, what is your inner for loop iterating from and to? You could probably simplify this to something more like
for k=1:length(vec)
zvec(vec(k)) = zvec(vec(k)) + 1;
end
where we just increment the appropriate element of zvec.
When trying to find the most frequent element, your use of max is correct but you could probably simplify it by having your call to this function return the index too (see max for details). You will then need to handle the case where you have more than two or more elements with the same frequency.
Of course, as soon as you include any number that is not a positive integer (-12, 42.3, etc.) then the above algorithm will have to be adjusted.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!