PETSc (Matlab ASCII) sparse matrix format


PETSc (the Portable, Extensible Toolkit for Scientific Computation) has an option for writing out sparse matrices to an ASCII text file which can be read by Matlab. This is true as of PETSc version 2.3.3 and probably much earlier (I checked on 12 Aug 2008). PETSc's interpretation of "can be read by Matlab" is different than our interpretation of "Matlab ASCII format." For the latter, we merely store an ASCII file of two, three, or four space-delimited columns of data. In contrast, PETSc actually generates a Matlab script: a source code file which can be interpreted by Matlab to produce the sparse matrix in the Matlab workspace. For example, a sparse matrix the SMC would store in Matlab (ASCII) format as

2 1  -1.0000000000000000e+00
1 2  -1.0000000000000000e+00
2 2  4.0000000000000000e+00
3 3  4.0000000000000000e+00
4 4  4.0000000000000000e+00
3 2  -1.0000000000000000e+00
2 3  -1.0000000000000000e+00
4 3  -1.0000000000000000e+00
3 4  -1.0000000000000000e+00
1 1  4.0000000000000000e+00
would be stored in PETSc's Matlab (ASCII) format as
% Size = 4 4
% Nonzeros = 10
zzz = zeros(10,3);
zzz = [
1 1  4.0000000000000000e+00
1 2  -1.0000000000000000e+00
2 1  -1.0000000000000000e+00
2 2  4.0000000000000000e+00
2 3  -1.0000000000000000e+00
3 2  -1.0000000000000000e+00
3 3  4.0000000000000000e+00
3 4  -1.0000000000000000e+00
4 3  -1.0000000000000000e+00
4 4  4.0000000000000000e+00
];
 Mat_0 = spconvert(zzz);
The latter, if run in Matlab, creates two variables in the workspace: "zzz", which is a scratch variable, and "Mat_0", which holds the sparse matrix. PETSc's interface lets users replace "Mat_0" with any desired name, as long as it is a valid Matlab variable. Both "zzz" and the matrix variable name would clobber any preexisting definitions of variables with the same name in the Matlab workspace.

PETSc's documentation does not explain (as of PETSc version 2.3.3) this output format. We had to look at the following source code file:

./mat/impls/aij/seq/aij.c
and a generated example contributed by an SMC user, in order to figure out the format. However, once you figure it out, it's not hard to parse or convert via a shell script to another format.