2017-03-08 37 views
0

在MATLAB中,说我有以下数据:在MATLAB将数据放入垃圾桶并计算平均

data = [4 0.1; 6 0.5; 3 0.8; 2 1.4; 7 1.6; 12 1.8; 9 1.9; 1 2.3; 5 2.5; 5 2.6]; 

我想根据在第2列(即元素以0-1在第一列放到垃圾箱,1-2,2-3 ...),并计算该单元内第1列元素的平均值和95%置信区间。所以我会有一个像这样的矩阵:

mean lower_95% upper_95% bin 
4.33       0 
7.5        1 
3.67       2 

回答

2

可以使用accumarray与平均值(mean)的适当功能或分位数(quantile):

m = accumarray(floor(data(:,2))+1, data(:,1), [], @mean); 
l = accumarray(floor(data(:,2))+1, data(:,1), [], @(x) quantile(x,.05)); 
u = accumarray(floor(data(:,2))+1, data(:,1), [], @(x) quantile(x,.95)); 
result = [m l u (0:numel(m)-1).']; 

这也可以用做电池阵列输出调用accumarray一次:

result = accumarray(floor(data(:,2))+1, data(:,1), [],... 
    @(x) {[mean(x) quantile(x,.05) quantile(x,.95)]}); 
result = cell2mat(result); 

为了您的数据。例如,

result = 
    4.3333 3.0000 6.0000   0 
    7.5000 2.0000 12.0000 1.0000 
    3.6667 1.0000 5.0000 2.0000 
+0

感谢@Luis Mendo - 也许我并不清楚,虽然 - 这似乎是我的数据的第二列(箱)的平均值,我想在第二列 – user2861089

+0

中指定的箱内第一列的均值和CI我编辑了任务离子稍微要更清楚 - 谢谢! – user2861089

+1

@ user2861089对不起,现在纠正 –

1

这会输出一个带有标记列的矩阵。请注意,对于您的示例数据,平均值的2个标准偏差(对于95% confidence interval)给出的频段之外的值。对于更大的(通常分布式)数据集,您不会看到这一点。

您的数据:

data = [4 0.1; 6 0.5; 3 0.8; 2 1.4; 7 1.6; 12 1.8; 9 1.9; 1 2.3; 5 2.5; 5 2.6]; 

分级输出表:

% Initialise output matrix. Columns: 
% Mean, lower 95%, upper 95%, bin left, bin right 
bins = [0 1; 1 2; 2 3]; 
out = zeros(size(bins,1),5); 
% Cycle through bins 
for ii = 1:size(bins,1) 
    % Store logical array of which elements fit in given bin 
    % You may want to include edge case for "greater than or equal to" leftmost bin. 
    % Alternatively you could make the left bin equal to "left bin - eps" = -eps 
    bin = data(:,2) > bins(ii,1) & data(:,2) <= bins(ii,2); 
    % Calculate mean, and mean +- 2*std deviation for confidence intervals 
    out(ii,1) = mean(data(bin,2)); 
    out(ii,2) = out(ii,1) - 2*std(data(bin,2)); 
    out(ii,3) = out(ii,1) + 2*std(data(bin,2)); 
end 
% Append bins to the matrix 
out(:,4:5) = bins; 

输出:

out = 

0.4667 -0.2357 1.1690   0 1.0000 
1.6750 1.2315 2.1185 1.0000 2.0000 
2.4667 2.1612 2.7722 2.0000 3.0000