Skip to content

Instantly share code, notes, and snippets.

@ffliza
Last active January 10, 2018 23:27
Show Gist options
  • Save ffliza/8df934e6adeaccc0d8a79f056a399852 to your computer and use it in GitHub Desktop.
Save ffliza/8df934e6adeaccc0d8a79f056a399852 to your computer and use it in GitHub Desktop.
%% The SVD demo with Covariance matrix
clear all;
clc;
% origin_mat = [2 4 6 8; 9 8 0 1]; %First original matrix 2x4
origin_mat = [2 4 6 8; 9 8 0 1; 5 3 -2 -3]; %Second original matrix 3x4
[u1, s1, v1]=svd(origin_mat);
sv=s1*v1';
origin_mat_hat=u1*sv; % reconstructed matrix
%% Now SVD with covariance matrix
%c = cov(origin_mat,origin_mat); % Try with first original matrix 2x4
c = origin_mat*origin_mat'; % Try with second original matrix 3x4
[u2,s2,v2]=svd(c);
p=u2'*origin_mat;
origin_mat_hat_cov = u2*p;
%% Reversing sign
%c = cov(origin_mat,origin_mat);
c = origin_mat*origin_mat'; % This form is easy to work with
[u2,s2,v2]=svd(c);
u2_rev_sign = u2 * -1; % reversing sign
p=u2_rev_sign'*origin_mat;
origin_mat_hat_cov_rev = u2_rev_sign * p;
%% Removing negativity
%c = cov(origin_mat,origin_mat);
c = origin_mat*origin_mat';
[u2,s2,v2]=svd(c);
u2_unsignd = abs(u2); % removing all negative sign
p=u2_unsignd'*origin_mat;
origin_mat_hat_cov_unsigned = u2_unsignd*p;
%% Summary
disp('------------------Summary--------------------------')
origin_mat
origin_mat_hat
origin_mat_hat_cov
origin_mat_hat_cov_rev
origin_mat_hat_cov_unsigned
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment