PCA using Matlab, SPSS

Hi
Following is the program I run for PCA. For the same set of data I tried PCA with various rotations in SPSS. But nothing gave the same plot as matlab did. Am I making any mistake in the program or why is the difference?
A=xlsread('sn30.xlsx');A = A';
[n m] = size(A);
AMean = mean(A);
AStd = std(A);
B = (A - repmat(AMean,[n 1])) ./ repmat(AStd,[n 1]);
[COEFF SCORE LATENT TSquare] = princomp(B);
PC1=SCORE;
A1=PC1(:,1);
B1=PC1(:,2);
C1=PC1(:,3);
for ii=1:8
plot3(A1(ii,1),B1(ii,1),C1(ii,1),'r*'); hold on;
end
for ii=9:15
plot3(A(ii,1),B1(ii,1),C1(ii,1),'bo'); hold on;
end
for ii=16:25
plot3(A(ii,1),B1(ii,1),C1(ii,1),'g^'); hold on;
end
Regards
Amutha

Answers (1)

Hi Amrutha,
When comparing PCA results between MATLAB and SPSS, there are several factors that can lead to differences in the plots, even when using the same dataset.Here's a cleaned-up version of your MATLAB code using pca, which is more modern and recommended over princomp:
% Read and preprocess data
A = xlsread('sn30.xlsx');
A = A';
[n, m] = size(A);
% Standardize the data
AMean = mean(A);
AStd = std(A);
B = (A - AMean) ./ AStd;
% Perform PCA
[coeff, score, latent, tsquare] = pca(B);
% Extract principal component scores
PC1 = score(:, 1);
PC2 = score(:, 2);
PC3 = score(:, 3);
% Plot the first three principal components
figure;
hold on;
for ii = 1:8
plot3(PC1(ii), PC2(ii), PC3(ii), 'r*');
end
for ii = 9:15
plot3(PC1(ii), PC2(ii), PC3(ii), 'bo');
end
for ii = 16:25
plot3(PC1(ii), PC2(ii), PC3(ii), 'g^');
end
xlabel('PC1');
ylabel('PC2');
zlabel('PC3');
title('PCA Plot');
grid on;
hold off;

Categories

Tags

Asked:

on 14 Apr 2012

Answered:

on 3 Feb 2025

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!