function matrix2latex(filename, matrix, varargin)
% MATRIX2LATEX Format LaTeX tabular data from matrix
%    MATRIX2LATEX(FILENAME, MATRIX, OUTFORMAT) writes the matrix in tabular
%    form that can be used in LaTeX, i.e. a '&' is added between the elements,
%    and each line is postfixed with '\\'.  Default output format is '%12.5e'.
%    Example: 
%              matrix2latex('file.txt', a)
%              matrix2latex('file.tex', a, '%.4f') 
%
%    Olaf Trygve Berglihn <olafb@pvv.org>

if length(varargin) == 0
    outformat = '%12.5e';
else
    outformat = varargin{1};
end
fid = fopen(filename, 'w');
[m,n] = size(matrix);
for i=1:m
    fprintf(fid, [outformat, ' & '], matrix(i,1:n-1));
    fprintf(fid, [outformat, '\\\\\n'], matrix(i,n));
end
fclose(fid);
