MATLAB: Pca() returns 1 less principal component

eigen valuespcaprincipal component

a = diag([1 2 3]);
disp(pca(a));
I expected that it will display 3 principal components, since my matrix "a" is full-rank 3-by-3 one. However, only two PCs are displayed. Actually, when I do the same in R, it does give me 3 PCs, the first two of which are exactly the same as the two that matlab provides.
However, when the number of row exceeds the number of columns, pca() function seems to work well, for example:
a = [diag([1 2 3]); 0, 0, 4];
disp(pca(a));
Is it because I didn't use pca() properly, or do I need to specify the style for the result to be displayed? Thanks…

Best Answer

See you need not to use inbuilt function for pca. Pca is straight forward with few steps. Check the below pca code with out using inbuilt pca function.
a = diag([1 2 3]);
% disp(pca(a));
A = cov(a) ; % co-variance matrix
[V,D] = eig(A) ; % GEt Eigenvalues and Eigenvectors
Eig = diag(D) ;
[val,idx] = sort(Eig,'descend') ;
PV = Eig(idx)
PC = V(:,idx)
disp(pca(a))
As you see one of the principal values (Eigenvalues) is zero. So pca is not displaying it.
Related Question