如何计算矩阵中给定值的元素数量?
有谁知道如何计算一个值在矩阵中出现的次数?
例如,如果我有一个 1500 x 1 矩阵 M
(向量),它存储工作日 (1 - 7) 的值,我如何计算有多少个周日 (1)、周一 (2)、 ... , 星期六(7) 存储在 M
中?
Does anyone know how to count the number of times a value appears in a matrix?
For example, if I have a 1500 x 1 matrix M
(vector) which stores the values of weekdays (1 - 7), how could I count how many Sundays (1), Mondays(2), ... , Saturdays(7) are stored in M
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
查看确定和计数数组的唯一值。
或者,要计算
5
出现的次数,只需执行以下操作Have a look at Determine and count unique values of an array.
Or, to count the number of occurrences of
5
, simply do以下是我能想到的计算唯一元素的所有方法的列表:
选项 1:制表
选项 2:hist/histc
选项 3:accumarray
选项 4:sort/diff
选项 5:arrayfun
选项 6:bsxfun
选项 7:稀疏
Here's a list of all the ways I could think of to counting unique elements:
Option 1: tabulate
Option 2: hist/histc
Option 3: accumarray
Option 4: sort/diff
Option 5: arrayfun
Option 6: bsxfun
Option 7: sparse
一次对所有值 1 到 7 执行此操作的一种方法是使用函数 ACCUMARRAY:
One way you can perform this operation for all the values 1 through 7 at once is to use the function ACCUMARRAY:
假设 w 包含周数 ([1:7]):
如果您不知道 M 中的数字范围,则
它就像 SQL Group by 命令!
assume w contains week numbers ([1:7])
if you do not know the range of numbers in M:
It is such as a SQL Group by command!
这将是完美的,因为我们正在矩阵上进行运算,答案应该是一个数字
this would be perfect cause we are doing operation on matrix, and the answer should be a single number
这是 Matlab Central File Exchange 上提供的一个非常好的函数文件。
countmember.m 链接
该函数文件完全矢量化,因此速度非常快。另外,与aioobe的答案中提到的函数相比,该函数不使用accumarray函数,这就是为什么它甚至与旧版本的Matlab兼容的原因。此外,它还适用于元胞数组和数值数组。
解决方案 :
您可以将此函数与内置的 matlab 函数“unique”结合使用。
occurrence_count将是一个与unique(M)大小相同的数值数组,occurrence_count数组的不同值将对应于unique(中相应值(相同索引)的计数米)。
This is a very good function file available on Matlab Central File Exchange.
countmember.m link
This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.
SOLUTION :
You can use this function in conjunction with the built in matlab function, "unique".
occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).
使用 nnz 代替 sum。不需要双重调用将矩阵折叠为向量,并且它可能比 sum 更快。
文档
Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.
Doc