% Picture of singular value decomposition
%
% Samuli Siltanen August 2012

% Create a matrix with random entries
reset(RandStream.getDefaultStream); % Reset random number generator
row = 10;
col = 6;
A = randn(row,col);

% Compute SVD. Here U and V are orthogonal square matrices, D is a diagonal 
% matrix containing the singular values along the diagonal in descending 
% order, and A = U*D*V.', where V.' is the transpose ov V.
[U,D,V] = svd(A);

% Construct a tailored colormap
colormap jet
MAP = colormap;
M = size(MAP,1); % Number of rows in the colormap
bckgrnd = [1 1 1]; % Pure white color
MAP = [bckgrnd;MAP];

% Create initial composite matrix for the image
im = ones(row,col+3+row+1+col+1+col);
MIN = min([A(:);U(:);D(:);V(:)]);
MAX = max([A(:);U(:);D(:);V(:)]);
cstep = (MAX-MIN)/(M-1); % Step size in the colorscale from min to max
im = (MIN-cstep)*im;

% Now insert the matrices A, U, D and V into matrix im
im(:,1:col) = A;
im(:,col+3+[1:row]) = U;
im(:,col+3+row+1+[1:col]) = D;
im(1:col,col+3+row+1+col+1+[1:col]) = V.';

% Show image of the matrice
figure(1)
clf
imagesc(im)
axis equal
axis off
colormap(MAP)
text(col+1.4,row/2,'=','fontsize',24)

% Save image to file
print -dpng SVDkuva.png