This repository has been archived on 2021-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
scientificComputing/linearalgebra/exercises/pca2d.m

40 lines
928 B
Matlab

n = 1000;
ds = [0:5];
for k = 1:length(ds)
d = ds(k);
% generate data:
x = randn(n, 1);
y = randn(n, 1);
y(1:n/2) = y(1:n/2) - d;
y(1+n/2:end) = y(1+n/2:end) + d;
% scatter plot of data:
subplot(2, 2, 1)
scatter(x, y, 'filled', 'MarkerEdgeColor', 'white')
title(sprintf('d=%g', d))
xlabel('x')
ylabel('y')
% histogram of data:
subplot(2, 2, 3)
hist(x, 20)
xlabel('x')
% pca:
cv = cov([x y]);
[ev en] = eig(cv);
[en inx] = sort(diag(en), 'descend');
nc = [x y]*ev(:,inx);
% scatter in new coordinates:
subplot(2, 2, 2)
scatter(nc(:, 1), nc(:, 2), 'filled', 'MarkerEdgeColor', 'white')
title(sprintf('d=%g', d))
xlabel('pca 1')
ylabel('pca 2')
% histogram of data:
subplot(2, 2, 4)
hist(nc(:, 1), 20)
xlabel('pca 1')
if d == 2
savefigpdf(gcf, 'pca2d-2.pdf', 15, 15);
end
pause(1.0)
end