+1 (315) 557-6473 

Matlab Program to Analyze Data Using PCA Assignment Solution.


Instructions

Objective
Write a matlab program to analyze data using PCA in matlab.

Requirements and Specifications

program to fit data in matlab

Source Code

clc, clear all, close all

load('TestData.dat');

X = TestData(:,1);

Y = TestData(:,2);

C = [X, Y];

mu = mean(C);

%% Question 1: Zero Mean Dataset

nomeanC = C - ones(size(C))*diag(mu);

%% Question 2: Plot original data and zero-mean data

f = figure

subplot(1,2,1)

scatter(C(:,1), C(:,2))

xlabel('X')

ylabel('Y')

grid on

title('(FIRST-NAME LAST-NAME) Original Dataset')

subplot(1,2,2)

scatter(nomeanC(:,1), nomeanC(:,2))

grid on

xlabel('{X-mean_{x}}')

ylabel('{Y-mean_{y}}')

title('(FIRST-NAME LAST-NAME) Zero Mean Dataset')

movegui(f, 'northwest')

%% Question 3

% Calculate eigenvalues and eigenvectors

[eigenvecs, eigenvals] = eigs(cov(nomeanC));

eigenvecs = -1*eigenvecs;

mapped = C*eigenvecs;

figure

scatter(mapped(:,1), mapped(:,2))

xlabel('{Mapped_{x}}')

ylabel('{Mapped_{y}}')

title('(FIRST-NAME LAST-NAME) Mapped to Principal Component')

grid on

%% Question 4:

% Define values of k

k = -6:6;

mu = mean(mapped(:,2));

sigma = std(mapped(:,2));

figure

% Plot data

plot(mapped(:,1), mapped(:,2), 'linewidth', 2), grid on

% Calculate lines

lines = mu+k*sigma;

hold on

legends = {'Data'};

for i = 1:length(lines)

    if lines(i) > 0 % positive lines

       plot([mapped(1,1), mapped(end,1)], [lines(i), lines(i)], 'linewidth', 2)

    end

    legends{i+1} = sprintf('sigma = %d', k(i));

end

xlabel('X')

ylabel('Y')

title('(FIRST-NAME LAST-NAME) Principal Component Plot')

legend(legends)

%% Question 5

f = figure

subplot(1,2,1)

scatter(C(:,1), C(:,2))

xlabel('X')

ylabel('Y')

grid on

title('(FIRST-NAME LAST-NAME) Original Dataset')

subplot(1,2,2)

scatter(nomeanC(:,1), nomeanC(:,2))

grid on

xlabel('{X-mean_{x}}')

ylabel('{Y-mean_{y}}')

title('(FIRST-NAME LAST-NAME) Zero Mean Dataset')

hold on

legends = {'Zero Mean Data'};

for i = 1:length(lines)

    if lines(i) > 0 % positive lines

       plot([nomeanC(1,1), nomeanC(end,1)], [lines(i), lines(i)], 'linewidth', 2)

    end

    legends{i+1} = sprintf('sigma = %d', k(i));

end

legend(legends)

movegui(f, 'northwest')