MATLAB provides a function mode that computes the mode of a set of values, that
ID: 3820740 • Letter: M
Question
MATLAB provides a function mode that computes the mode of a set of values, that is, the single most frequently occuring value (in the case of a tie, it returns the smallest value among those having the maximum frequency). For example, the command m = mode([5 8 2 9 2 5 7 2 6 5 4]) sets variable m to the value 2, as it and 5 occurs three times each, with 2 chosen based on the tie-breaking rule. There is a second form of the command [m n] = mode(V) where m is the value of the mode and n is its frequency. For example, the command [m n] = mode([5 8 2 9 2 5 7 2 6 5 4]) sets m = 2 and n = 3.
Your task is to implement a function called myMode(v) that has similar behavior when called upon a vector of values. You are not allowed to use the official mode function. However, you may use the built-in function sort which sorts values of a vector into non-decreasing order. Once the data is sorted, finding the mode is equivalent to looking for the longest consecutive streak of equal values.
Explanation / Answer
%matlab code
function [m n] = myMode(x)
% sorting the vector
for i=1:length(x)
for j=1:length(x)
if x(i) < x(j)
t = x(i);
x(i) = x(j);
x(j) = t;
end
end
end
% find number with highest frequency
m = x(1);
maxCount = 1;
count = 1;
for i=2:length(x)
if (x(i) != x(i-1))
if count > maxCount
maxCount = count;
m = x(i-1);
end
count = 1;
else
count = count + 1;
end
end
n = maxCount;
end
% test array
v = [5 8 2 9 2 5 7 2 6 5 4]
[m n] =myMode(v)
%{
output:
x =
5 8 2 9 2 5 7 2 6 5 4
m = 2
n = 3
%}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.