簡體   English   中英

Matlab:協方差矩陣錯誤的結果

[英]Matlab: Covariance Matrix wrong result

我必須計算Covaiance矩陣才能進行PCA,但是每當我用來自Matlab的協方差矩陣resul(使用Cov函數)比較我的協方差矩陣結果時,它就會給出不同的結果。

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

這是我的程序:

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 Cov函數給出的協方差矩陣結果

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

有人可以幫我解決這個問題嗎,我已經問過了,但沒人回答。.T_T

你讓事情變得復雜

嘗試這個

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不是Rows *列,而分母應該是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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM