MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of MATLAB Mathematics - SERC - Index of

serc.iisc.ernet.in
from serc.iisc.ernet.in More from this publisher
15.11.2014 Views

6 Sparse Matrices Manipulating Sparse Matrices Because sparse matrices are stored in a column-major format, accessing the matrix by columns is more efficient than by rows. Compare the time required for adding rows of a matrix 1000 times S = sparse(10000,10000,1); tic; for n = 1:1000 A = S(100,:) + S(200,:); end; toc Elapsed time is 1.208162 seconds. versus the time required for adding columns S = sparse(10000,10000,1); tic; for n = 1:1000 B = S(:,100) + S(:,200); end; toc Elapsed time is 0.088747 seconds. When possible, you can transpose the matrix, perform operations on the columns, and then retranspose the result: S = sparse(10000,10000,1); tic; for n = 1:1000 A = S(100,:)' + S(200,:)'; A = A'; end; toc Elapsed time is 0.597142 seconds. The time required to transpose the matrix is negligible. Note that the sparse matrix memory requirements may prevent you from transposing a sparse matrix having a large number of rows. This might occur even when the number of nonzero values is small. 6-42

Sparse Matrix Operations Using linear indexing to access or assign an element in a large sparse matrix will fail if the linear index exceeds intmax. To access an element whose linear index is greater than intmax, use array indexing: S = spalloc(216^2, 216^2, 2) S(1) = 1 S(end) = 1 S(216^2,216^2) = 1 6-43

6 Sparse Matrices<br />

Manipulating Sparse Matrices<br />

Because sparse matrices are stored in a column-major format, accessing the<br />

matrix by columns is more efficient than by rows. Compare the time required<br />

for adding rows <strong>of</strong> a matrix 1000 times<br />

S = sparse(10000,10000,1);<br />

tic;<br />

for n = 1:1000<br />

A = S(100,:) + S(200,:);<br />

end;<br />

toc<br />

Elapsed time is 1.208162 seconds.<br />

versus the time required for adding columns<br />

S = sparse(10000,10000,1);<br />

tic;<br />

for n = 1:1000<br />

B = S(:,100) + S(:,200);<br />

end;<br />

toc<br />

Elapsed time is 0.088747 seconds.<br />

When possible, you can transpose the matrix, perform operations on the<br />

columns, and then retranspose the result:<br />

S = sparse(10000,10000,1);<br />

tic;<br />

for n = 1:1000<br />

A = S(100,:)' + S(200,:)';<br />

A = A';<br />

end;<br />

toc<br />

Elapsed time is 0.597142 seconds.<br />

The time required to transpose the matrix is negligible. Note that the sparse<br />

matrix memory requirements may prevent you from transposing a sparse<br />

matrix having a large number <strong>of</strong> rows. This might occur even when the number<br />

<strong>of</strong> nonzero values is small.<br />

6-42

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

Saved successfully!

Ooh no, something went wrong!