Performance 用matlab计算观测值的个数
我有一个matlab数据集,如下所示:Performance 用matlab计算观测值的个数,performance,matlab,count,accumarray,Performance,Matlab,Count,Accumarray,我有一个matlab数据集,如下所示: year value 1995 90000 1995 53000 1995 80000 1995 60000 1995 37000 1995 42000 1995 13102 1996 35000 1996 50000 1996 32000 1996 47000 1997 36000 1997 90000 1997 NaN 1997 90000 1997 51
year value
1995 90000
1995 53000
1995 80000
1995 60000
1995 37000
1995 42000
1995 13102
1996 35000
1996 50000
1996 32000
1996 47000
1997 36000
1997 90000
1997 NaN
1997 90000
1997 51500
1997 81000
1998 71000
(...)
2020 68000
这是两列独立的数据
现在,我想计算2010年至2020年间每年value
列中非NaN观测值的数量,即输出应如下所示:
year count
2010 20
2011 31
(...)
2020 9
如果任何计数为零,则应显示为零
我知道我可以用一个非常简单的循环来完成(下面的例子)。但对于大型数据集来说,这是非常低效的。我正在研究accumarray,但不知道该怎么做
N = 300;
%Generate years vector
years = round(1996 + (2020-1996) .* (rand(N,1)));
years = sort(years);
% Generate values vector
values = rand(N,1);
NaN_position = rand(N,1)>.9; %Now put some random NaNs
values(NaN_position) = NaN;
count = 1;
for y=min(years):max(years)
indicator = years == y;
count_vals(count,1) = sum(not(isnan(values(indicator))));
count = count + 1;
end
将数据定义为:
years = [1995 1995 1995 1995 1995 1995 1995 1996 1996 1996 1996 1997 1997 1997 1997 1997 1997 1998 2020].';
values = [90000 53000 80000 60000 37000 42000 13102 35000 50000 32000 47000 36000 90000 NaN 90000 51500 81000 71000 68000].';
year_min = 1996;
year_max = 1998;
然后:
在第二次输入
histcounts
时需要术语year\u max+.5
,因为根据,最后一个箱子包括右边缘。。非常感谢。
result_year = year_min:year_max;
result_count = histcounts(years(~isnan(values)), [result_year year_max+.5]);