作者YoursEver (银英传出webgame!?)
看板MATLAB
标题Re: [讨论] 在一个矩阵中找出最多出现次数的向量
时间Fri Jul 15 14:58:03 2016
※ 引述《popo14777 (草草)》之铭言:
: 小弟的程式如下
: A=[0 0 0 0 0 17 17 19 19 19 17 17 17 17 17]
: B=[0 0 0 0 0 22 22 24 24 24 24 24 24 24 24]
: C=[A;B]
: 0,0 出现5次
: 17,22 出现2次
: 19,24 出现3次
: 17,24 出现4次
: 直向量的个数有15个
: 在C的一个矩阵下挑出次数最多的直向量,且要最少个数,还要不包含零
: 所以挑第11组(17,24)的直向量,并取得11这个数值
: 小弟还有其他矩阵,例如矩阵为11*15(这个范例是2*15)
: 请问大大这样的程式要如何写呢?
: 谢谢
假设你的C是 3-by-N, 2D int array,
(因此不需考虑round off error) <= 这个版本不需考虑round off error
%%%%
01 function [idx, vec] = find_mode_vec( C )
02
03 array_max = max( C(:) );
04 R3_to_R1_mapping = [(array_max+1)*(array_max+1), array_max+1, 1]*C;
05
06 most_freq_entry = mode(R3_to_R1_mapping);
07
08
09 idx = find( R3_to_R1_mapping, most_freq_entry, 'first');
10 vec = C(:, idx);
11
12 end
只适用於 max( C(:) ) 不太大的case,
如果太大, 请另设 R3_to_R1_mapping 所该使用的mapping function.
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.109.22.216
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/MATLAB/M.1468565886.A.1BA.html
※ 编辑: YoursEver (140.109.22.216), 07/15/2016 15:00:16
1F:推 popo14777: 谢谢Y大,我run出来出现这个错误讯息 07/16 01:12
Please excuase me that I cannot use Chinese now.
If your matri C is a 2-by-N matrix,
use the following line instead:
R3_to_R1_mapping = [array_max+1, 1] * C;
※ 编辑: YoursEver (218.161.51.131), 07/16/2016 05:36:59
3F:推 popo14777: 谢谢Y大,这次是出现这个讯息.. 07/16 14:54
I made a mistake.
Please use the function below:
01 function [idx, vec] = find_mode_vec( C )
02 array_max = max( C(:) );
03 R3_to_R1_mapping = [ array_max+1, 1]*C
+ 1;
04
05 % most_freq_entry = mode(R3_to_R1_mapping);
06
07 % if most_freq_entry==1
08 R3_to_R1_without_1 = R3_to_R1_mapping(R3_to_R1_mapping~=1);
09 most_freq_entry = mode(R3_to_R1_without_1);
10 % end
11
12 idx = find(
R3_to_R1_mapping==most_freq_entry, 1);
13 vec = C(:, idx);
14 end
※ 编辑: YoursEver (218.161.51.131), 07/16/2016 18:14:26
※ 编辑: YoursEver (218.161.51.131), 07/16/2016 18:15:35
※ 编辑: YoursEver (218.161.51.131), 07/16/2016 18:17:35
※ 编辑: YoursEver (218.161.51.131), 07/16/2016 18:22:18
5F:→ popo14777: 谢谢Y大,感谢你.. 07/17 09:37
6F:推 popo14777: 补推 07/17 09:48
7F:推 name0625: Y大还上色!太用心了! 07/18 12:10