Print sparse matrix in IJV, COO format in matlab

Alec Jacobson

November 30, 2010

weblog/

Here's a very simple way to print sparse matrices. It uses IJV or coordinate (COO) format. For every non-zero entry Sij in the sparse matrix S we print a line:
i j v
where v is the non-zero value in S at row i, column j. Here's the matlab function:
function printIJV(file_name,S)
  [i,j,v] = find(S);
  file_id = fopen(file_name,'wt');
  # uncomment this to have the first line be:
  # num_rows num_cols
  #fprintf(file_id,'%d %d\n', size(S));
  fprintf(file_id,'%d %d %g\n',[i-1,j-1,v]');
  fclose(file_id);
end
Note: I'm converting from MATLAB's one-indexed system to zero-indexed.