如何计算矩阵中给定值的元素数?

时间:2010-05-21 09:29:50

标签: matlab count matrix

有谁知道如何计算值在矩阵中出现的次数?

例如,如果我有一个1500 x 1矩阵M(向量)存储工作日的值(1 - 7),我怎么能计算星期日(1),星期一(2)的数量, ...,星期六(7)存储在M

7 个答案:

答案 0 :(得分:97)

查看Determine and count unique values of an array

或者,要计算5的出现次数,只需执行

即可
sum(your_matrix == 5)

答案 1 :(得分:73)

以下列出了我可以想到的计算独特元素的所有方法:

M = randi([1 7], [1500 1]);

选项1:制表

t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);

选项2:hist / histc

counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );

选项3:accumarray

counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);

选项4:sort / diff

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);

选项5:arrayfun

counts5 = arrayfun( @(x)sum(M==x), unique(M) );

选项6:bsxfun

counts6 = sum( bsxfun(@eq, M, unique(M)') )';

选项7:稀疏

counts7 = full(sparse(M,1,1));

答案 2 :(得分:10)

您可以同时对所有值1到7执行此操作的一种方法是使用函数ACCUMARRAY

>> M = randi(7,1500,1);  %# Some random sample data with the values 1 through 7
>> dayCounts = accumarray(M,1)  %# Will return a 7-by-1 vector

dayCounts =

   218       %# Number of Sundays
   200       %# Number of Mondays
   213       %# Number of Tuesdays
   220       %# Number of Wednesdays
   234       %# Number of Thursdays
   219       %# Number of Fridays
   196       %# Number of Saturdays

答案 3 :(得分:5)

假设w包含周数([1:7])

n = histc(M,w)

如果您不知道M中的数字范围:

n = histc(M,unique(M))

它是一个SQL Group by command!

答案 4 :(得分:4)

这将是完美的,因为我们正在对矩阵进行操作,答案应该是单个数字

sum(sum(matrix==value))

答案 5 :(得分:3)

这是一个非常好的功能文件,可在Matlab Central File Exchange上找到。

countmember.m link

此函数文件完全矢量化,因此非常快。另外,与aioobe的答案中提到的功能相比,此功能不使用accumarray功能,这就是为什么它甚至与旧版本的Matlab兼容。此外,它适用于单元格数组和数字数组。

解决方案: 您可以将此函数与内置的matlab函数“unique”结合使用。

  

occurance_count = countmember(unique(M),M)

occurance_count将是一个数字数组,其大小与唯一(M)相同,并且occunce_count数组的不同值将对应于唯一(M)中相应值(相同索引)的计数。

答案 6 :(得分:2)

使用nnz而不是sum。不需要双向调用将矩阵折叠到向量,它可能比求和更快。

nnz(your_matrix == 5)

Doc

相关问题