2014-02-13 140 views
0

我必須計算Covaiance矩陣來做PCA,但是無論何時我將協方差矩陣結果與matlab中的協方差矩陣結果(使用Cov函數)相比較,它會給出不同的結果。Matlab:協方差矩陣錯誤結果

所以這意味着我的程序是錯誤的。

這是我的計劃:

InputMatrix=[1 2 3; 4 5 6; 9 1 2]; 
Average=mean(InputMatrix); 
[Rows,Columns]=size(InputMatrix); 

DataNumbers=Rows*Columns; 

%% Substraction 
for loop_row=1:Rows 
    for loop_column=1:Columns 
     Substract_Matrix(loop_row,loop_column)=InputMatrix(loop_row,loop_column)-Average(loop_column); 
    end 
end 

%% Transpose 
for loop1=1:Rows 
    for loop2=1:Columns 
     Transpose_Matrix(loop2,loop1)=Substract_Matrix(loop1,loop2); 
    end 
end 


%% Multiply 
CovarianceMatrix=(Substract_Matrix*Transpose_Matrix)*1/DataNumbers; 

通過我的程序給出的協方差矩陣輸出:

1.5926 -0.0741 -1.5185 
-0.0741 1.2593 -1.1852 
-1.5185 -1.1852 2.7037 

協方差矩陣結果通過Matlab的冠狀病毒功能

16.3333 -3.1667 -3.1667 
-3.1667 4.3333 4.3333 
-3.1667 4.3333 4.3333 

誰能幫定我解決這個問題, 我已經問過它,bu沒有人回答wered尚未.. T_T

+0

[協方差矩陣與Matlab的不同結果?](http://stackoverflow.com/questions/21741963/cov ariance-matrix-different-result-with-matlab) – nkjt

回答

1

你在做的事情複雜

試試這個

InputMatrix=[1 2 3; 4 5 6; 9 1 2]; 
ave_matrix = repmat(mean(InputMatrix),3,1) 
(InputMatrix-ave_matrix)'*(InputMatrix-ave_matrix)/2 % sample_num -1 which is 3-1 

我看到你要去哪裏錯了,DataNumbers是不是行*列 和分母應該是DataNumbers - 1

InputMatrix=[1 2 3; 4 5 6; 9 1 2]; 
Average=mean(InputMatrix); 
[Rows,Columns]=size(InputMatrix); 

DataNumbers=Columns; 

%% Substraction 
for loop_row=1:Rows 
    for loop_column=1:Columns 
     Substract_Matrix(loop_row,loop_column)=InputMatrix(loop_row,loop_column)-Average(loop_column); 
    end 
end 

%% Transpose 
for loop1=1:Rows 
    for loop2=1:Columns 
     Transpose_Matrix(loop2,loop1)=Substract_Matrix(loop1,loop2); 
    end 
end 


%% Multiply 
CovarianceMatrix=(Transpose_Matrix*Substract_Matrix)/(DataNumbers-1); 
+0

你是否知道如何在同一幅圖中繪製InputMatrix與Mean的關係圖 %figure(2) %imshow(ImSeq(:,:1) ,[]) 保持在 圖(InputMatrix,「.R‘) 圖(平均,’.G」) 推遲 但也有很多點的身影,而我只需要繪製的3分輸入和1點的意思 – user3303896