Print diagonal matrices in matlab

Alec Jacobson

November 30, 2010

weblog/

Here's a very simple matlab function that prints the main diagonal of a matrix, one line per entry:
function printDiagonal(file_name,D)
  file_id = fopen(file_name,'wt');
  # uncomment this to have the first line be:
  # length_of_main_diagonal
  #fprintf(file_id,'%d\n', min(size(D)));
  fprintf(file_id,'%g\n',full(diag(D)));
  fclose(file_id);
end
Update: I add the full(...) command to make sure this works even if the D passed is a sparse matrix.