2011-12-14 51 views
3

我想寫這樣的代碼爲兩個矩陣:如何找出y中每個數組的平均值,它們在x中具有相同的指數?

x=[1 1 1 2 2 3 3 3 3]'; 
y=[11 21 31 24 32 33 13 37 3]'; 

我怎樣才能找出每個組的y個的平均值,即在X相同的指數?

我的算法是這樣的:

If  x(1)=x(2) counter1=1 sum1=y(1)+y(2) 
     x(2)=x(3) counter1=2 sum1=sum+y(3) Define newx1=x(1) newy1=sum1/counter1 
     x(3)<>x(4) 
     x(4)=x(5) counter2=1 sum2=y(4)+y(3) Define newx2=x(4) newy2=sum2/counter2 
     x(5)<>x(6) 
     x(6)=x(7) counter3=1 sum3=y(6)+y(7) 
     x(7)=x(8) counter3=2 sum3=sum+y(8) 
     x(8)=x(9) counter3=3 sum3=sum+y(9) Define newx1=x(6) newy3=sum3/counter3 

我的問題就在這裏被使用在一個循環中兩個以上的計數器。也許,我應該寫類似:

s=1:8 
for k=1:9 
if x(k)=x(k+s); 
else 
s=s+1; 
end 
end 

沒有工作:( 我會greatfull任何幫助或建議

+4

這對我毫無意義。你能否澄清你想要做什麼?另外,你知道Matlab有一個高度優化的「平均」函數,對吧? – PengOne 2011-12-14 19:06:01

回答

1

如果我理解正確的話,你希望每個平均。組具有相同的索引中的「X」在這種情況下的數字...

function FindAverages 
x=[1 1 1 2 2 3 3 3 3]'; 
y=[11 21 31 24 32 33 13 37 3]'; 

means = []; 
indexes = unique(x); 
for i=1:numel(indexes) 
    index = indexes(i); 
    indexInY = (x==index); 
    means(end+1) = mean(y(indexInY)); 
end 
disp(means); 
1

一種解決方案是使用統計工具箱中可用GRPSTATS功能,它可以通過組應用功能:

x=[1 1 1 2 2 3 3 3 3]'; 
y=[11 21 31 24 32 33 13 37 3]'; 
grpstats(y,x,@mean) 

替代選項(如果您沒有統計工具箱,例如))在FileExchange上使用GROUP2CELL提交。它將對應於特定類別的數字放入單元格陣列中的單獨單元格中。如果我理解正確你的問題,你可以簡單地使用accumarray,它應該工作快則一環

cellfun(@mean,group2cell(y,x)) 
0

:那麼你可以申請很多功能,包括與CELLFUN平均值。

%#Input 
x=[1 1 1 2 2 3 3 3 3]'; 
y=[11 21 31 24 32 33 13 37 3]'; 

[newx, idx]=unique(x,'legacy'); 
newy=accumarray(x(:),y(:),[],@mean); %#groups every element of 'y' according to the index of 'x' and applies the function '@fun' to each group. 
%#Output 
newy =[21.0000 28.0000 21.5000]; 
newx=[1 2 3];  %#returns the index used for each group 
idx=[3 5 9];  %#returns the index of the last observation for each group 
相關問題