%
% CS515 sparse matrix demo
% Lecture 16, 10/21
%

% full matrix format
A = [
1 0 0 0;
2 -1 0 0;
1.5 0 -1 0;
-1 0 0 1
]

%% disassemble into TRIPLET format:
[Is Js As] = find(A);
disp({'Is ',' Js ',' As'})
disp([Is Js As])

%% re-assemble into CSC format using "sparse" command:
B = sparse(Is,Js,As) % displays in TRIPLET format, but is stored in CSC

%% prove B = A by looking at dense format:
C = full(B)
A-C


%%
% Speed test

n = 1000;
% create sparse matrix with random entries on diagonal
A = spdiags(randn(n,1),1,n,n);
x = randn(n,1);
y = x;

tic;
for j=1:2000
x = A*x;
end
toc

B = full(A);
tic;
for j=1:2000
y =B*y;
end
toc

norm(x-y)