2011-11-13 118 views
1

我有2個不同的文件,其中之一是一個輸入矩陣(X),它具有3823 * 63個元素(3823個輸入和63個特徵),另一個是類矢量( R),其具有3823 * 1個元素;那些元素的值從0到9(有10個類)。Matlab不同類的協方差矩陣計算

我必須計算每個類的協方差矩陣。到目前爲止,我只能爲每個具有這麼多嵌套循環的類計算平均向量。然而,它導致我腦死亡。

有沒有其他簡單的方法?


有我的目的代碼(感謝薩姆·羅伯茨):

xTra = importdata('optdigits.tra'); 
xTra = xTra(:,2:64); % first column's inputs are all zero 

rTra = importdata('optdigits.tra'); 
rTra = rTra(:,65); % classes of the data 

c = numel(unique(rTra)); 

for i = 1:c 
    rTrai = (rTra==i-1); % Get indices of the elements from the ith class 
    meanvect{i} = mean(xTra(rTrai,:)); % Calculate their mean 
    covmat{i} = cov(xTra(rTrai,:)); % Calculate their covariance 
end 
+0

你確定這是必要的嗎?你可能會有一個完全不同的應用程序,所以如果是這樣的話,我會很單調,但我不熟悉使用類標籤計算協方差。例如,我計算一個cov矩陣作爲PCA的謂詞步驟,但所需的結果只是一個二維矩陣(n x n),給出了特徵的成對協方差(這是我需要的特徵向量計算)。我/ o/w類標籤不是必需的。 – doug

+0

@doug我要編輯問題並添加一個標籤。 – onatm

回答

2

這是否你需要什麼?

X = rand(3263,63); 
R = randi(10,3263,1)-1; 

numClasses = numel(unique(R)); 

for i = 1:numClasses 
    Ri = (R==i); % Get indices of the elements from the ith class 
    meanvect{i} = mean(X(Ri,:)); % Calculate their mean 
    covmat{i} = cov(X(Ri,:)); % Calculate their covariance 
end 

此代碼遍歷每個類中,選擇R個的對應於觀察從該類的行,然後從X得到相同的行並計算它們的平均值和協方差。它將它們存儲在單元陣列中,因此您可以像這樣訪問結果:

% Display the mean vector of class 1 
meanvect{1} 

% Display the covariance matrix of class 2 
covmat{2} 

希望對您有所幫助!

+0

電腦神的神聖母親,這是什麼樣的魔法?非常感謝! – onatm

+0

是的 - 通常MATLAB的一點是它可以讓你不必爲嵌套循環做所有的事情。矩陣計算是內置的! –

+0

我之前使用了平均和cov函數,但是我沒有在細胞結構中使用它們。再次感謝你的答案,並教我如何使用細胞。 – onatm

0

首先構造每個類的數據矩陣。 第二個計算每個數據矩陣的協方差。

下面的代碼是這樣做的。

% assume allData contains all the data you've read in, each row is one data point 
% assume classVector contains the class of each data point 
numClasses = 10; 
data = cell(10,1);  %use cells to store each of the data matrices 
covariance = cell(10,1); %store each of the class covariance matrices 
[numData dummy] = size(allData); 

%get the data out of allData and into each class' data matrix 
%there is probably a nice matrix way to do this, but this is hopefully clearer 
for i = 1:numData 
    currentClass = classVector(i) + 1; %Matlab indexes from 1 
    currentData = allData(i,:); 
    data{currentClass} = [data{currentClass}; currentData]; 
end 

%calculate the covariance matrix for each class 
for i = 1:numClasses 
    covariance{i} = cov(data{i}); 
end 
+0

是的,好的矩陣索引由[Sam Roberts](http://stackoverflow.com/users/169781/sam-roberts)解決。 –

1

不要使用meansum作爲一個變量的名字,因爲他們是有用的Matlab的內置函數的名稱。 (使用幫助的類型爲doc meandoc sum

另外cov會爲您計算協方差矩陣。

您可以使用邏輯索引來提取示例。

covarianceMatrices = cell(m,1); 
for k=0:m-1 
    covarianceMatrices{k} = cov(xTra(rTra==k,:)); 
end 

的一行

covarianceMatrices = arrayfun(@(k) cov(xTra(rTra==k,:)), 0:m-1, 'UniformOutput', false); 
+1

適用於單線解決方案。 – onatm