有没有更优雅的替代品可以替代此MATLAB循环? [英] Is there a more elegant replacement for this MATLAB loop?
问题描述
我想更好地在MATLAB中向量化我的循环.目前,我正在尝试计算int列表中值的出现次数.我的代码与此类似:
I want to get better at vectorizing my loops in MATLAB. At the moment, I'm trying to count the occurrences of values in a list of ints. My code is similar to this:
list = [1 2 2 3 1 3 2 2 2 1 5];
occurrence_list = zeros(1,max(list));
for x=list
occurrence_list(x) = occurrence_list(x) + 1;
end
是否有一个简单的向量化替代for循环? (或者我缺少一个内置的MATLAB函数吗?)我正在非常小的数据集上执行此操作,因此时间不是问题.我只想改善我的MATLAB编码风格.
Is there a simple vectorized replacement for that for loop? (Or is there a built in MATLAB function that I'm missing?) I'm doing this on pretty small data sets, so time isn't an issue. I just want to improve my MATLAB coding style.
推荐答案
除了HIST/HISTC函数之外,您还可以使用ACCUMARRAY来计算发生次数(以及许多其他聚合操作)
In addition to the HIST/HISTC functions, you can use the ACCUMARRAY to count occurrence (as well as a number of other aggregation operations)
counts = accumarray(list(:), 1)
%# same as: accumarray(list(:), ones(size(list(:))), [], @sum)
另一种方法是使用统计工具箱中的TABULATE(返回值,计数,频率):
Another way is to use TABULATE from the Statistics Toolbox (returns value,count,frequency):
t = tabulate(list)
t =
1 3 27.273
2 5 45.455
3 2 18.182
4 0 0
5 1 9.0909
请注意,如果值不是从1m开始,或者在最小值和最大值之间存在较大差距的情况下,在计数之间会出现很多零.而是使用:
Note that in cases where the values don't start at 1m or in case there's large gaps between the min and the max, you will get a lot of zeros in-between the counts. Instead use:
list = [3 11 12 12 13 11 13 12 12 12 11 15];
v = unique(list);
table = [v ; histc(list,v)]'
table =
3 1
11 3
12 5
13 2
15 1
代表唯一值及其计数(这只会列出至少出现一次的值)
representing the unique values and their counts (this will only list values with at least one occurrence)
这篇关于有没有更优雅的替代品可以替代此MATLAB循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!