Tuesday 3 September 2013

Generating Latex table of Matlab/Octave Matrix


I created some code in Octave/Matlab to generate latex table from matrix data. I created this because in my case I was tuning some data and algorithms for a paper I was writing and I loathed entering my data into the latex over and over in large tables.

The use just needs to supply a file descriptor, names for the table rows, column, the data matrix and if desired a wrapper to wrap the data entries from the matric in any specific formatting.


Example wrapper functions



function outstr = numWrapper(value)

outstr= strcat("\\num{" , num2str (value), "}");

endfunction
function outstr = ccolWrapper(value)
outstr= strcat("\\ccol{" , num2str (value), "}");
endfunction
 
 


This is the code used to generate the latex
 


%
% creates a latex style table from matrix data.
% wrapper is a function used to wrap the data in each cell
% can be used to apply more formatting in latex
%
% fid is the file pointer to the file to write to
% matrix is the data matrix that will be placed starting at row 1 column 1
% rowNames is a column vector of the string names to be inserted as the names for the rows
% size(rowNames,1) == size(columnNames,1)+1, i.e. the
% columnNames will be used to label each of the column in the data
% wrapper is a special function that will take your input data and wrap it with latex formatting
%
% Will look like
% latex table formatting
% columnNames[0] | columnNames[1] | columnNames[2] | columnNames[2] | ...
% rowNames[0] | matrix(0,0) | matrix(0,1) | matrix(0,2) | ...
% rowNames[1] | matrix(1,0) | matrix(1,1) | matrix(1,2) | ...
% .
% .
% .
%
%
%
%
% latex table formating
function fid = matrixToLatexTable(fid, matrix, rowNames, columnNames, wrapper )
fprintf(fid,'\\documentclass{article}\n');
fprintf(fid,'\\begin{document}\n');
fprintf(fid,' \\begin{tabular}{ |');
for col=1:size(matrix,2)+1
fprintf(fid,'c | ');
end
fprintf(fid,'}\n\\hline\n');
for col=1:size(columnNames,1)
if col==size(columnNames,1)
fprintf(fid,' %s', columnNames(col,:))
else
fprintf(fid,' %s & ', columnNames(col,:))
end
end
fprintf(fid,'\n \\\\ \\hline\n');
% now write the elements of the matrix
for r=1:size(matrix,1)
fprintf(fid,' %s & ', rowNames(r,:))
for c=1:size(matrix,2)
if c==size(matrix,2)
if true
fprintf(fid,'%s ',wrapper(matrix(r,c)));
else
fprintf(fid,'%f ', matrix(r,c));
end
else
if true
fprintf(fid,'%s & ',wrapper(matrix(r,c)));
else
fprintf(fid,'%f & ', matrix(r,c));
end
end
end
fprintf(fid,' \\\\ \\hline \n');
end
fprintf(fid,'\\end{tabular}\n');
fprintf(fid,'\\end{document}\n');
fclose(fid);
endfunction
 
 
Best of luck
- Glen