%         MATLAB TUTORIAL for PHYS 460/660
%    Accelerated algorithms for sparce matrices
%------------------------------------------------

% SPARSE MATRIX is a matrix with LARGE procentage of zero elements
% When dealing with sparse matrices, it is desirable to take advantage of
% the sparsity by storing and operating only on the nonzeros


% A=sparse(i,j,s) defines a sparse matrix A of dimension max(i)-by-max(j)
% with A(i(k),j(k))=s(k), for k=1:5 and all other elements zero

A=sparse([1 2 2 4 4],[3 1 4 2 4], 1:5)

B=full(A) % Convert sparse matrix into full matrix

A=sparse(B) % Convert full matrix into sparse storage format

whos % Check the amount of storage used

% B consists of 16 double precision numbers of 8 bytes each = 128 bytes
% n x n matrix with nnz nonzeros requires 8*nnz+4*(nnz+n+1)

sparse(4,5) % sparse matrix of zeros

speye(4) % identity sparse matrix

spones(A) % same sparsity pattern as A but with ones in the nonzero positions

% C=spdiags(D,d,m,n) creates m-by-n matrix C whose diagonals indexed by d
% are taken from the columns of D

D=[1 2 0; 1 2 3; 0 2 3; 0 2 3]

d=[-2 0 1]

C=spdiags(D,d,4,4)

full(C)

% Note that subdiagonals are taken from the leading parts of the columns of
% D and the superdiagonals from the trailing parts

[B,d]=spdiags(A) % Diagonals can be extracted also with spdiag

% Seting up particular tridiagonal matrix
n=5; e=ones(n,1)
A=spdiags([-e 4*e -e],[-1 0 1],n,n)
full(A)

% MATALAB can solve sparse linear equations, eigenvalue, and singular value
% problems, taking advantage of sparsity

doc 'arithmetic operators'







