2014-02-13 139 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