The sparse
function is normally used to create sparse matrices but it has a trick up its sleeve! This post reveals one of my favorite MATLAB tricks.
When used with the tuple syntax, sparse(i,j,v)
or sparse(i,j,v,m,n)
, any repeated (i,j) elements are automatically accumulated! In other words, the sparse
function automatically sums any values that are assigned to the same location.
This is in contrast to normal array assignment where a statement like
A(i+(j-1)*m) = v;
(for a full array A) overwrites any repeated elements (leaving only the last value assigned in that spot).
The accumulation behavior can be used in some cases to enhance performance. For example, the following code uses sparse
to compute the image histogram for an indexed image (the code also displays the histogram counts as a bar chart).
% Load one of the MATLAB demo images.
% The mat-file contains:
% X - the index image matrix
% map - its colormap
load durer
counts = sparse(1,X,1);
bar(counts)
By mapping all the image values to a single row, the accumulation feature of sparse
automatically computes the histogram counts!
accumarray
Current versions of MATLAB also contain a function called accumarray
that performs the accumulation trick for non-sparse matrices (and you can change the accumulation function too). The accumarray
function is even more powerful than sparse
because it includes options to set the fill value to something other than zero and it handles cell arrays too.