~ubuntu-branches/ubuntu/natty/suitesparse/natty

« back to all changes in this revision

Viewing changes to CSparse/MATLAB/Demo/private/ex_1.m

  • Committer: Bazaar Package Importer
  • Author(s): Christophe Prud'homme
  • Date: 2006-12-22 10:16:15 UTC
  • Revision ID: james.westby@ubuntu.com-20061222101615-2ohaj8902oix2rnk
Tags: upstream-2.3.1
ImportĀ upstreamĀ versionĀ 2.3.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
function ex_1
 
2
%EX_1: four methods for creating the same matrix.
 
3
%   (please wait, this can take a while...)
 
4
 
 
5
% Example:
 
6
%   ex_1
 
7
% See also: cs_demo
 
8
 
 
9
%   Copyright 2006, Timothy A. Davis.
 
10
%   http://www.cise.ufl.edu/research/sparse
 
11
 
 
12
n = 1000 ;
 
13
nz = 1e5 ;
 
14
 
 
15
tic
 
16
% method 1: A(i,j) = ...
 
17
rand ('state', 0) ;
 
18
A = sparse (n,n) ;
 
19
for k = 1:nz
 
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)) ;
 
23
    x = rand (1) ;
 
24
    A (i,j) = A (i,j) + x ; % VERY slow, esp. if A(i,j) not already nonzero!
 
25
end
 
26
fprintf ('Method 1: ') ;
 
27
toc
 
28
A1 = A ;
 
29
 
 
30
tic
 
31
% method 2: triplet form, one entry at a time
 
32
rand ('state', 0) ;
 
33
ii = zeros (nz, 1) ;    % preallocate ii, jj, and xx
 
34
jj = zeros (nz, 1) ;
 
35
xx = zeros (nz, 1) ;
 
36
for k = 1:nz
 
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)) ;
 
40
    xx (k) = rand (1) ;
 
41
end
 
42
A = sparse (ii,jj,xx) ;
 
43
fprintf ('Method 2: ') ;
 
44
toc
 
45
A2 = A ;
 
46
disp (A1-A2) ;
 
47
 
 
48
tic
 
49
% method 3: triplet form, one entry at a time, pretend nz is unknown
 
50
rand ('state', 0) ;
 
51
len = 16 ;
 
52
ii = zeros (len, 1) ;
 
53
jj = zeros (len, 1) ;
 
54
xx = zeros (len, 1) ;
 
55
for k = 1:nz
 
56
    % compute some arbitrary entry and add it into the matrix
 
57
    if (k > len)
 
58
        % double the size of ii,jj,xx
 
59
        len = 2*len ;
 
60
        ii (len) = 0 ;
 
61
        jj (len) = 0 ;
 
62
        xx (len) = 0 ;
 
63
    end
 
64
    ii (k) = 1 + fix (n * rand (1)) ;
 
65
    jj (k) = 1 + fix (n * rand (1)) ;
 
66
    xx (k) = rand (1) ;
 
67
end
 
68
A = sparse (ii (1:k), jj (1:k), xx (1:k)) ;
 
69
fprintf ('Method 3: ') ;
 
70
toc
 
71
 
 
72
A3 = A ;
 
73
disp (A1-A3) ;
 
74
 
 
75
tic
 
76
% method 4: avoid the for loop
 
77
rand ('state', 0) ;
 
78
e = rand (3, nz) ;
 
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: ') ;
 
83
toc
 
84
 
 
85
A4 = A ;
 
86
disp (A1-A4) ;