% sparseMatrices.m
% Illustration of sparse matrices in Matlab.
% K. Ming Leung, 11/17/04

clear all;
format short;

% a full 4x4 matrix
F = [ 0 0 1 0; 2 0 0 3; 0 0 0 0; 0 4 0 5],

% the same matrix represented as a sparse matrix
S = sparse([1 2 2 4 4],[3 1 4 2 4],[1 2 3 4 5]),

% the ordering of the elements is unimportant
% the same matrix can be created by
S1 = sparse([2 4 1 2 4],[1 2 3 4 4],[2 4 1 3 5]),

% a full matrix can be converted to a sparse matrix
SF = sparse(F),

% sparse matrix can be converted to a full matrix
FS = full(S),

% number of non-zeros in a sparse matrix is given by
n = nnz(S)

% one can check the amount of storage by

whos S F


S2 = gallery('wathen',8,8);
subplot(121), spy(S2), subplot(122), spy(chol(S2)),

% creates a 4x7 sparse matrix of zeros
S3 = sparse(4,7)
% same as
S4 = sparse([],[],[],4,7,0)

% creates an nxn sparse identity matrix
S5 = speye(n)
% same as
S6 = speye(n,n)

% creates a sparse matrix having the same sparcity pattern 
% as S and with ones in the non-zero positions
S7 = spones(S)


[Vi,Vj,Vs] = find(S);
[m,n] = size(S);
S8 = sparse(Vi,Vj,Vs,m,n);

% an example of an adjacency matrix
S9 = sparse([1 1 2 2 3 3 4 4],[2 4 1 3 2 4 1 3],1,4,4),
F9 = full(S9),

% Columns of gplot's coordinate array contain the Cartesian coordinates 
% for the corresponding node. 
% For the diamond example, create the array by entering

xy = [1 3; 2 1; 3 3; 2 5];

% This places the 1st node at location (1,3), 
% the 2nd at (2,1), the 3rd at (3,3), and the 4th at (2,5). 
% To view the resulting graph, enter

gplot(S9,xy); axis([0 4 0 6]);
text(xy(:,1),xy(:,2),['1';'2';'3';'4'],'fontsize',16);

