how to find mode without built-in mode function?

6 ビュー (過去 30 日間)
dana
dana 2013 年 6 月 9 日
コメント済み: the cyclist 2021 年 1 月 7 日
any suggestions how to write a function that finds a vectors mode WITHOUT using the built-in mode function?

回答 (3 件)

the cyclist
the cyclist 2013 年 6 月 9 日
You could use the hist() function, and use the value that has the highest count.
  5 件のコメント
the cyclist
the cyclist 2021 年 1 月 7 日
I think this is because by default, hist() chooses the bin centers by an algorithm that does not guarantee they are in the original vector. Try this instead:
[counts, centers] = histcounts(YourVector,[unique(YourVector) Inf]);
[~, maxidx] = max(counts);
mode_value = centers(maxidx);
the cyclist
the cyclist 2021 年 1 月 7 日
I realized that that code will not find all the modes, if there are multiple. This code should:
[counts, centers] = histcounts(YourVector,[unique(YourVector) Inf]);
max_value = max(counts);
max_idx = (counts==max_value);
mode_values = centers(max_idx)

サインインしてコメントする。


Walter Roberson
Walter Roberson 2013 年 6 月 9 日
unique(), take the third output, put it through accumarray(), find the max()

Roger Stafford
Roger Stafford 2013 年 6 月 9 日
編集済み: Roger Stafford 2013 年 6 月 9 日
If you are not allowed to use the 'mode' function, it sounds as though you must use only more primitive functions. Are you allowed to do the following with v as the given column vector?
u = sort(v);
f = find([true;diff(u)~=0;true]);
[~,ix] = max(diff(f));
m = u(f(ix)); % m is most frequent value occurring in v
(Corrected)
  5 件のコメント
Rik
Rik 2021 年 1 月 6 日
That depends on the dimensions of v. If it is a column vector this runs without error.
v = [9;4;2;4;9;2;4];
u = sort(v);
[true;diff(u)~=0;true]
ans = 8x1 logical array
1 0 1 0 0 1 0 1
v = [9;4;2;4;9;2;4];
v = v.';
u = sort(v);
[true;diff(u)~=0;true]
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Louise Wade
Louise Wade 2021 年 1 月 7 日
編集済み: Louise Wade 2021 年 1 月 7 日
I'll try and transpose my row vector into a column vector and try again. If there are multiple values as the mode, would this cause an issue?
EDIT: It seems to be working for me. Thank you so much for helping. All I needed to do was transpose the array.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating, Deleting, and Querying Graphics Objects についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by