2
%EX_1: four methods for creating the same matrix.
3
% (please wait, this can take a while...)
9
% Copyright 2006, Timothy A. Davis.
10
% http://www.cise.ufl.edu/research/sparse
16
% method 1: A(i,j) = ...
20
% compute some arbitrary entry and add it into the matrix
21
i = 1 + fix (n * rand (1)) ;
22
j = 1 + fix (n * rand (1)) ;
24
A (i,j) = A (i,j) + x ; % VERY slow, esp. if A(i,j) not already nonzero!
26
fprintf ('Method 1: ') ;
31
% method 2: triplet form, one entry at a time
33
ii = zeros (nz, 1) ; % preallocate ii, jj, and xx
37
% compute some arbitrary entry and add it into the matrix
38
ii (k) = 1 + fix (n * rand (1)) ;
39
jj (k) = 1 + fix (n * rand (1)) ;
42
A = sparse (ii,jj,xx) ;
43
fprintf ('Method 2: ') ;
49
% method 3: triplet form, one entry at a time, pretend nz is unknown
56
% compute some arbitrary entry and add it into the matrix
58
% double the size of ii,jj,xx
64
ii (k) = 1 + fix (n * rand (1)) ;
65
jj (k) = 1 + fix (n * rand (1)) ;
68
A = sparse (ii (1:k), jj (1:k), xx (1:k)) ;
69
fprintf ('Method 3: ') ;
76
% method 4: avoid the for loop
79
e (1,:) = 1 + fix (n * e (1,:)) ;
80
e (2,:) = 1 + fix (n * e (2,:)) ;
81
A = sparse (e (1,:), e (2,:), e (3,:)) ;
82
fprintf ('Method 4: ') ;