2011-05-13 223 views
1

我有一個有n行和n列的矩陣,我想每次平均做10行的binning,這意味着最後我剩下一個大小爲n/10的矩陣, ñ。我添加了matlab庫,並嘗試了下面的代碼:矩陣的Binning平均值

nRemove = rem(size(a,1),10); 
a = a(1:end-nRemove,:)  
Avg = mean(reshape(a,10,[],n)); 
AvgF = squeeze(Avg); 

但它沒有工作,我應該使用哪個代碼/代碼?

謝謝!

回答

1
t(sapply(1:(NROW(A)/10), function(x) colMeans(A[ x:(x+9), ]))) 

您需要轉置操作來重新定位結果。經常需要在「應用」操作之後這樣做。

3

這裏是另一種方式來做到這一點:這將導致

  NA  NA.1  NA.2  NA.3  NA.4  NA.5  NA.6  NA.7 
1 0.5295264 0.5957229 0.4502069 0.5168083 0.3398190 0.4075922 0.6059122 0.5127865 
2 0.4778341 0.3967321 0.4069635 0.4514742 0.6172677 0.2486085 0.6340686 0.4052600 
3 0.5168132 0.5117207 0.5202261 0.5068593 0.5218041 0.4925462 0.5169584 0.4919296 
4 0.3299557 0.3314723 0.4503393 0.3965103 0.6166598 0.5525628 0.4943880 0.6048207 
5 0.6145423 0.5853235 0.4822182 0.3377771 0.3540784 0.5974846 0.5202577 0.5769518 
6 0.5009249 0.5203701 0.3940540 0.4237508 0.3199265 0.4817713 0.4655320 0.6124400 
7 0.7335082 0.5856578 0.3929621 0.6403662 0.5347719 0.5658542 0.4226456 0.7196593 
8 0.4976663 0.5205538 0.4529273 0.4757352 0.6980300 0.5694570 0.4384924 0.5481236 
9 0.5275932 0.5014861 0.5363340 0.5664576 0.5006055 0.5611069 0.3803889 0.4680865 
10 0.4560031 0.5527328 0.4419076 0.6893043 0.5161281 0.5895931 0.3965911 0.3842419 
     NA.8  NA.9 
1 0.3711607 0.5541607 
2 0.4379255 0.4159131 
3 0.5048523 0.5884052 
4 0.4642687 0.4572388 
5 0.6054209 0.5174784 
6 0.4659952 0.5332438 
7 0.4568273 0.3943798 
8 0.6978356 0.5087778 
9 0.4897584 0.4710949 
10 0.6310546 0.4775762 

set.seed(5) 

x = matrix(runif(1000), ncol = 10) 
nr = nrow(x) 
gr = rep(1:floor(nr/10), each = 10) 
aggregate(x ~ gr, FUN=mean)[,-1]