How intelligently does Matlab deal with sparse matrix operations?

4 views (last 30 days)
I am curious about how Matlab deals with sparse matrices:
Knowing that all of the matrices I am operating on are defined as (or built as) sparse matrices throughout my code (e.g., A = spalloc(n,n,nzmax), and then elements are added to A), can I be sure that Matlab is dealing with them intelligently when I loop through the elements in a row and perform arithmetic operations? Meaning, do I need to do anything in particular to ensure that Matlab only deals with the nonzero elements in a sparse matrix, or will the "sparse" designation handle that for me under the hood?
Thanks in advance.

Accepted Answer

Cedric Wannaz
Cedric Wannaz on 24 Jan 2013
Edited: Cedric Wannaz on 24 Jan 2013
A sparse matrix doesn't contain its 0 elements, so internally they won't be taken into account by built-ins that support sparse matrix computations. There are built-ins that will not work on sparse matrices though (or at least there were in previous versions of MATLAB), but I don't remember which ones. I have no memory of any automatic conversion to full however. Now if you code explicit loops over all elements, MATLAB won't prevent you from looping over all zeros elements.
PS: I am using sparse matrices a lot, but with a limited field of application (linear systems, differential equations, emulate accumarray in specific situations, ..). So you might discover functions that I have never been dealing with, that convert automatically to full. If they exist, it would be interesting to keep a record.
EDIT: for more information, see e.g.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!