Tuesday, February 11, 2014

Matlab spconvert function - undocumented "feature"

Matlab has a useful function for loading data that is in a sparse format - spconvert.  Basically, you create a file where each row contains the row, column, and data of the matrix you wish to load.  The first column is indicates the destination row, the second column indicates the destination column and the third column indicates the value at that row and column.  You load that into matlab (using, e.g., csvread):
sparse = csvread('mydata.csv');

example:
sparse = [1 1 2
2 1 3
2 2 5
3 3 7];

"sparse" is now have a N by 3 matrix, where N is the number of non-zero entries in your data.  With the command:
mat = spconvert(sparse)

yields:
2 0 0
3 5 0
0 0 7

Warning!!!! This doesn't appear to be documented!!! If you repeat a location in sparse, the value that appears in the result (mat) will be the sum of the entries in sparse.  For example, if sparse is modified to be:
sparse = [1 1 2
2 1 3
2 2 5
3 3 7
1 1 11];

then mat = spconvert(sparse) yields:
13 0 0
3 5 0
0 0 7

Note that the (1,1) entry of mat is 13, the sum of 2 + 11, the first and last rows of sparse.

No comments:

Post a Comment