Question

I have to calculate Covaiance Matrix to do PCA, but whenever I compae my Covariance Matrix result with the covariance matrix resul from matlab (using Cov function), it gives different result.

So it means that my program is wrong.

Here is my Program:

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;

The Covariance Matrix Output given by my program :

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

Covariance Matrix Result given by Matlab Cov Function

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

Can someone help me to solve this, I already asked about it, bu no one answered yet.. T_T

Was it helpful?

Solution

you are making things complicated

try this

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

I see where you are going wrong , the DataNumbers is not Rows* columns and the denominator should be 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top