15.11.2014 Views

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sparse Matrix Operations<br />

Performance Limitations<br />

This section describes some limitations <strong>of</strong> the sparse matrix storage format and<br />

their impact on matrix creation, manipulation, and operations.<br />

Creating Sparse Matrices<br />

The best way to create a sparse matrix is to use the sparse function. If you do<br />

not have prior knowledge <strong>of</strong> the nonzero indices or their values, it is much more<br />

efficient to create the vectors containing these values and then create the<br />

sparse matrix.<br />

Preallocating the memory for a sparse matrix and filling it in an elementwise<br />

manner causes a significant amount <strong>of</strong> overhead in indexing into the sparse<br />

array:<br />

S1 = spalloc(1000,1000,100000);<br />

tic;<br />

for n = 1:100000<br />

i = ceil(1000*rand(1,1));<br />

j = ceil(1000*rand(1,1));<br />

S1(i,j) = rand(1,1);<br />

end<br />

toc<br />

Elapsed time is 26.281000 seconds.<br />

Whereas constructing the vectors <strong>of</strong> indices and values eliminates the need to<br />

index into the sparse array, and thus is significantly faster:<br />

i = ceil(1000*rand(100000,1));<br />

j = ceil(1000*rand(100000,1));<br />

v = zeros(size(i));<br />

for n = 1:100000<br />

v(n) = rand(1,1);<br />

end<br />

tic;<br />

S2 = sparse(i,j,v,1000,1000);<br />

toc<br />

Elapsed time is 0.078000 seconds.<br />

6-41

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!