2017-03-08 58 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