clear; clc; close all;

A = rgb2gray(imread('taipei101.jpg')); % gray level
figure; imshow(A);
A = double(A); % convert to doubles
[U, S ,V] = svd(A);

pc = min(size(A));
k = round(pc * [0.01, 0.02, 0.04, 0.08, 0.16]);
res = zeros(1, length(k));

for i = 1 : length(k)
    s = 1 : k(i);
    tmp = U(:, s) * S(s, s) * V(:, s)';
    res(i) = mse(A - tmp);
    tmp = uint8(tmp); % back to uint8
    figure; imshow(tmp);
    pause();
end

figure; plot(k, res, '.--'); grid on;
xlabel('Number of principal components');
ylabel('MSE');
