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);