File Exchange

## latexTable

version 1.21 (17.6 KB) by

Converts matrices, cells and MATLAB tables to LaTex table code. Allows format,pivot,col/row headers.

4.91304
27 Ratings

Updated

Converts matrices, cells or MATLAB tables to LaTeX table code. Easy to use and very flexible:
- takes MATLAB matrices, cells or tables as input
- gives code for a LaTeX table containing your data as output
- handles numeric and text/string data
- easy including in your code for automation
- easy direct saving as a LaTex document (see example 2 in runExamples.m)
Optional features are:
- table positioning
- column/row labels
- column/row-wise formatting (like setting the number of digits etc.)
- pivoting the table (90 degree rotation making columns rows and vice versa)
- setting the default symbol for NaN values
- LaTeX column alignment
- LaTeX table borders, caption, label
- output a complete LaTeX document instead of a plain table
A little example:
input.data=[1,3;4,2]; % set up data
latexTable(input) % obtain LaTeX code
For further details and examples can be found in latexTable.m and runExamples.m

Pengfei Zhao

### Pengfei Zhao (view profile)

Is there a way to combine cell and double entries for table objects ?
For example, I have stored the number of hidden units for neural networks in a cell array like :
hunits={[10,10],[20,20,20]}.
Additionaly there is something like the learning rate, which is in double format.
They are both columns in a matlab table object. However, I can't combine both columns.
Is there a workaround ?

Hi! I have code, for example:
syms M;
A=[1+M 2];
input.data = A;
latex=latexTable(input);
I get the error message. Can I fix it or latexTable can not be used with syms?

Stefan Boeters

### Stefan Boeters (view profile)

I have tried your script with the following table:

RBC_table =

9×7 table

Var Std rStd Corr aCorr lag lead
____ _____ ____ _____ _____ _____ ____

'Y' 5.59 1 1 0.9 0.73 0.73
'C' 4.42 0.79 0.25 0.9 0.01 0.05
'I' 14.33 2.56 0.03 0.98 -0.19 0.12
'L' 6.34 1.13 0.81 0.79 0.46 0.49
'lp' 3.75 0.67 0.12 0.86 0.3 0.25
'w' 4.42 0.79 0.2 0.91 0.27 0.09
'M' 11.81 2.11 -0.09 0.97 -0.16 0.04
'X' 10.41 1.86 0.47 0.98 0.39 0.45
'Pi' 0.72 0.13 0.22 0.44 0.05 0.01

but then I get the error message:

Error using latexTable (line 111)
To assign to or create a variable in a table, the number of rows must match the height of the table.

Any idea about what goes wrong?

dengpingjun

### dengpingjun (view profile)

Hi,Duenisch,
Thanks, this toolbox is very good. but I find a little issue in it. that is, when the data is cell or table type, the latex cannot contain different types of the elements. For example,

Data={1,2;[1,2],[2,3]};
Input.data=Data;
Input.makeCompleteLatexDocument = 1;
LatexCode=latexTable(Input);

The above codes generate following results:

\documentclass[a4paper,10pt]{article}
\begin{document}
\begin{table}
\centering
\begin{tabular}{|c|c|}
\hline
 &  \\
\hline
 &  \\
\hline
\end{tabular}
\caption{MyTableCaption}
\label{table:MyTableLabel}
\end{table}
\end{document}

Nothing is in the table! why?

Thanks.

AlessandroM

LouiseG

### LouiseG (view profile)

Hi, I am trying to use this function for a project. What I get is a matrix of functions (ex 4/3) when my input is a matrix of scientific style numbers (1.333) . How I can I force the function to give as output the same format of numbers as in the original matrix?
Thanks!

Max Dekoninck

### Max Dekoninck (view profile)

i had an issue, if i used num2cell to parse the row or column labels to text it did not use the same formatting as the other data in the table, i added these line as a temporary solution:

tmp2 = repmat(tmp(:,1),[1 cellSize(2)+rowLabelsExist]);
if colLabelsExist
tmp2 = cat(1,tmp2(1,:),tmp2);
end
dataFormatArray = cell(cellSize);
dataFormatArray(1:end,1:end) = tmp2;

otherwise thanks for this package!

defrunze

### defrunze (view profile)

Thanks, Eli! That definitely helped a lot.

The copy-paste is no longer a problem.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi defrunze,

You could achieve floating-point formatting by setting a well-suited formatSpec in input.dataFormat. For example if you use '%.9g' there will print out nine significant digits ignoring the position of the decimal point:

disp(num2str(123.456789,'%.9g'));
disp(num2str(1.23456789,'%.9g'));

The copy&paste problem in yout LaTex editor:
If this is still a problem - could you provide a short version of the LaTex code that reproduces the error (via email)?

I hope that helps.

defrunze

### defrunze (view profile)

Hi Eli,

Whenever I convert an array to a latexTable, I get numbers in fixed point format. Is there any way to get them in floating point format?

defrunze

### defrunze (view profile)

Hi Eli,
when i copy-paste the output into TeX editor and typeset, it gives me an error that has something to do with \hline commands and \centering.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Benjamin,
if you want to use the table placement option (current version of latexTable),
just set up the input struct like in this little example:

input.tablePlacement='H'; % table placement parameter
input.data = magic(3); % get some data
latex = latexTable(input);

This should add the placement parameter in brackets [H] to the resulting LaTex code:

\begin{table}[H]
\centering
\begin{tabular}{|c|c|c|}
...

One thing to remember is that depending on your LaTex compiler settings, included packages etc. positioning might behave differently.
I'm not sure if that answers your question. If not just let me know.

Benjamin Leiva

### Benjamin Leiva (view profile)

Thanks Eli. I got the first part, but I could not figure out how to incorporate the table position command. I have the current version, and replaced everywhere in the following command with 'H' as you specified, but it did not work.

% Placement of the table in LaTex document
if isfield(input,'tablePlacement') && (length(input.tablePlacement)>0)
input.tablePlacement = ['[',input.tablePlacement,']'];
else
input.tablePlacement = '';
end

AN H just appears besides the table.

Thanks so much for your help

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Benjamin,
setting column and/or row-labels should actually be ok. Could you please provide
an example that reproduces the error? Here is some code that should work:

clc;clear input; % clear previous stuff
input.data = magic(3); % get some data
input.tableColLabels = {'col1','col2','col3'}; % col labels
input.tableRowLabels = {'row1','row2','row4'}; % row labels
latex = latexTable(input);

Having an option to include the table position is a good point - I've included
it now in the current version. For example:
...
input.tablePlacement = 'H';
...
If you want to stick with the old version you may use the following workaround:
% set up the input struct and run the function as usual
input.data = magic(3);
latex = latexTable(input);
% then ...
clc; % clear command window for convenience
latex{1}='\begin{table}[H]'; % overwrite first line
disp(char(latex)); % print altered code

Benjamin Leiva

### Benjamin Leiva (view profile)

Hi Eli, I have two questions:

The first, is that the input.tableColLabels does not work for me, whereas the input.tableRowLabels does (and I am doing the same thing for both). Might there be a mistake with the first?

The second follows Chocolateee: when exporting to latex, I get that the table is pasted at the top of the page. This could manually be solved by copying and pasting the code and forcing the location with [H], but that attempts against the automation just achieved. Is there a way to manage this issue?

Thank you! Your package is great!

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Chocolateee,
here is an example how to save your code as a .tex file:

% the data
input.data = [1.12345 NaN 3.12345; ...
4.12345 5.12345 6.12345; ...
7.12345 8.12345 9.12345; ...
10.12345 11.12345 12.12345];
% we want a complete LaTex document
input.makeCompleteLatexDocument = 1;
% generate LaTex code
latex = latexTable(input);
% save LaTex code as file
fid=fopen('MyLatex.tex','w');
[nrows,ncols] = size(latex);
for row = 1:nrows
fprintf(fid,'%s\n',latex{row,:});
end
fclose(fid);

I think I will add this to the example code. Thank you for your feedback.

Chocolateee

### Chocolateee (view profile)

Hi Eli, this function works beautifully! One question, what is the most convenient way to save the cell output into a tex file that can be included into my main tex file? I tried with fprintf and save but had little success. You may consider include this feature in the future.

Chocolateee

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi ExtremeOPS,
thank you for your feedback and the feature proposals. It's great that you are offering to contribute to the code - for the individual features please open pull requests (a link to the github repository can be found below the download button on this page). Of course you will be mentioned in the author section afterwards.
Here are my two cents about the proposed features:
- file-saving should be handeled by the embedding script because this function should be kept as simple/reduced as possible
- individual column alignment should be a new feature
- printing the generated LaTex code should be optional, enabled by default

Again thank you for your time and valuable feedback.
Best

ExtremOPS

### ExtremOPS (view profile)

Hi Eli,

I really like your function! It does all the basic jobs you want to have.

I just added for myself the following stuff:
- function for saving the file in a specific folder; I needed to add for this input.savename and input.savefolder
- changed the function so not all columns have the same alignment type but you can choose manually; I did it the same way how you did it with the input.format
- and also the option of not showing the output in the command window; default setting is showing

I can add this to your code if you like you just need to tell me how to this and I will.

In the meantime I thank you very much for your work.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

@Anders thank you for the hint - helps to make this little tool better. It is fixed now.

Troels Landbo

### Troels Landbo (view profile)

Doing all the data processing in relation with the Bachelor project at this moment. This meant that the raw data was appended in the PDF report and not only in a zip file. Thanks

Anders

### Anders (view profile)

Very nice function.
A little bug with the representation of NaN. The field you check for is not the one the user should input:

% Define what should happen with NaN values in input.tableData:
if ~isfield(input,'nanString'),input.dataNanString = '-';end

Egle Jakucionyte

robertosangi

### robertosangi (view profile)

You're the best. I never use a function and for thar reason it doesn't play. Thanks for support and for all!

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

This looks to me like the function is not in your current MATLAB search path. Copy latexTable.m to your current working directory. If your MATLAB setup is ok the code provided in runExamples.m should run without errors.
Feel free to send me some part of your code as a PM or Pastebin link. This should be fixed easily.

robertosangi

### robertosangi (view profile)

Nothing to do... Now Matlab give me this message:
Undefined function or variable 'latexTable'

I wrote:

myTable=T;
input.data=myTable;
latexTable(input)

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Roberto,
I guess the error comes from giving your table the name 'latexTable' which will shadow the function with the same name. Just choose a different name for the table:

% some MATLAB table
myTable=table(magic(5));

% store table in input struct
input.data=myTable;

% call function
latexTable(input)

If it doesn't work, let me know.

robertosangi

### robertosangi (view profile)

The function give me a message:
I call my table
latexTable
I write
input.data=latexTable
At least i write
latex=latexTable(input)

And Matlab give me:
You cannot subscript a tablr using only one subscript. Table subscripting requires both row and variable subscripts.

Can you help me? Can you give me all meticulous passages to generate my latex table? Thanks

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Luc, as far as I know all files published here are licensed according to BSD (not sure whether other licenses are allowed). To make it more obvious I will include the advertising clause in the code. Best, Eli

Luc Le Magoarou

### Luc Le Magoarou (view profile)

Hi ELi,

under which license do you distribute your code ? If it is not specified, redistribution under any form is not allowed, that is why I ask this question.

Thanks for the great code anyway,

Luc

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Seeda, the code runs for string data as well. Please make sure to put LaTex code that is included in your data in $...$ environments. There was a little bug for handling MATLAB tables labels which should be fixed now. I also included a new example in runExamples.m using strings including LaTex code. Have fun :)

Seeda

### Seeda (view profile)

Has someone figured out how to make latexTable.m to work with string entries? I took the suggestions I saw in the comments but did not work for me.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

I'm sorry but I cannot reproduce the issues. Best thing would be that you send me an example and the latexTable.m that you are using. Which version of MATLAB are you using? input.tableRowLabels should work fine, try runing the examples given in runExamples.m. If you don't need row labels just do not set the field.

Joseph Cullen

### Joseph Cullen (view profile)

The updates to the program fixed the problems. There are a couple more issues that popped up.
1. input.tableRowLabels doesn't seem to do anything. input.tableColLabels works as it would be expected
2. I am getting strange results from input.dataFormat where all of the numbers in the row correctly formatted except for the first one.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Joseph, it seems that you are using an older or modified version of the code (line 87 in the current version just contains a comment). In order to run the function properly you should stick to the field names given in the examples/comment section. If you use different names the function will inevitably throw errors. I hope that helps.

Joseph Cullen

### Joseph Cullen (view profile)

get the following error when running the examples.
need to change to using input.tableData rather than input.data

Reference to non-existent field 'tableData'.

Error in latexTable (line 87)
if strcmp(class(input.tableData),'table')

Error in runExamples (line 57)
latex = latexTable(input);

Joseph Cullen

### Joseph Cullen (view profile)

This is outputing a latex table that is a transpose of the table I am providing. Setting the input.transposeTable = 0 or to 1 does not seem to make a difference.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi vivi, thank you for your feedback. You are right, the code asumed that row and column names are given when using a MATLAB table. I fixed that now by setting the corresponding input fields only if names are given. Hope that helps.

vivi

### vivi (view profile)

I have found what I think is a bug. This happens only when using the matlab table( ) command and if row names are not assigned in the table( ) command, even though they are assigned via input.tableColLabels. This is the error I get:

Subscripted assignment dimension mismatch.

Error in latexTable (line 116)
C(1,1+rowLabelsExist:end)=input.tableColLabels;

Error in plots (line 62)
latex = latexTable(input);

This is happening because this part of the code
% process table datatype
if isa(input.data,'table')
input.tableColLabels = input.data.Properties.RowNames';
input.tableRowLabels = input.data.Properties.VariableNames';
input.data = table2array(input.data)';
end

creates the field input.tableColLabels, and then the test

colLabelsExist = isfield(input,'tableColLabels');

returns a 1, even though there are no tableColLabels created originally. Then when the script tries to write the row names in the table via this statement

if colLabelsExist
C(1,1+rowLabelsExist:end)=input.tableColLabels;
end

the error occurs since input.tableColLabels = { }

Sargondjani

### Sargondjani (view profile)

Works like a charm!!! :D ... this seriously reduces the time I waste on editing :p

JMP Phillips

### JMP Phillips (view profile)

Hello, the file in its current version only supports numeric tables, and so isnan(dataValue) will throw an error if dataValue is a string.

For this reason I propose the following simple modification to latexTable to support tables of strings or text rather than numbers:

% generate table
for i=1:size(C,1)
if input.tableBorders
latex(end+1) = {hLine};
end
rowStr = '';
for j=1:size(C,2)
dataValue = C{i,j};
if iscell(dataValue)
dataValue = dataValue{:};
elseif isnan(dataValue)
dataValue = input.dataNanString;
elseif isnumeric(dataValue)
dataValue = num2str(dataValue,dataFormatArray{i,j});
end
if j==1
rowStr = dataValue;
else
rowStr = [rowStr,' & ',dataValue];
end
end
latex(end+1) = {[rowStr,' \\']};
end

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

I forgot to mention the following workflow:
2. make a struct containing data (and additional parameters if you want to): input.data=M;input.tableColLabels=...;...
3. call function with the struct: latexTable(input)

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

@David Please make sure that the data you want to plot is given as a struct. The struct needs to contain a field named 'data' which contains the data values you want to put in the LaTex table. For example lets assume your data is stored as a matrix M in the MATLAB workspace. Then use input.data = M to obtain the struct. After that call latexTable(input). You may also add other parameters to the struct to modify some properties of the LaTex table. For details please have a look at the header section of the function or runExamples.m. Let me know if you have any further questions.

David Stevens

### David Stevens (view profile)

Hi, Thanks you very much for this great input!
I would like to convert a '*.mat' into a LaTex file. Unfortunately while running this function I just get the error message
"Reference to non-existent field 'data'.
Error in latexTable (line 96)
if isa(input.data,'table')".
Do you have any idea how can I convert this "*.mat" into a LaTex file ussing this function? Thanks!

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi, as far as I know MATLAB does not offer a built-in functionality to convert decimal numbers to engineering notation strings.
However you there is a function here at the file exchange called 'num2eng'. Another approach can be found here http://www.mathworks.com/matlabcentral/answers/892-engineering-notation-printed-into-files

Sebastian Stoelen

### Sebastian Stoelen (view profile)

Works perfectly! However, my table entries are really small values, is there any way to specify that the entries should appear in engineering notation rather than with a fixed number of digits after the decimal point?

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

the function gives a cell array as output, so you may use the following code to avoid copy&paste:

latex = latexTable(input);
fid=fopen('laTexFile.tex','w');
for i=1:size(latex,1)
fprintf(fid, '%s\n', latex{i});
end
fclose(fid);

I'll think about including the code in runExamples.m or in the function itself.

Manuel

### Manuel (view profile)

Wonderful. Works like a charm.
Could you also maybe add a functionality where I can save this table in .tex file at user defined location.
This way I could easily import my code into latex using \input{.tex}, rather than copying and pasting every time.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

I just fixed the output when no row or column labels are set. Thank you Dimitar :)

@Jan
Thank you for mentioning this. Maybe I will implement your approach using a loop and repmat for the formatting in the next update.

Dimitar Atanasov

### Dimitar Atanasov (view profile)

cellSize = [numberDataRows+colLabelsExist,numberDataCols+rowLabelsExist];

Should be like this

Andreas Trier Poulsen

Jan Kubanek

### Jan Kubanek (view profile)

Good.
I needed a more flexible formatting of the columns or rows, like this:
input.dataFormat = {'%.1f', [1 3 5], '%.3f', [2 4 6]};
This sets different formats for particular columns (alternating in this example).

To do so, simply change the loop starting with
for i=1:2:lengthDataFormat

TO
for i=1:2:lengthDataFormat
dataFormatList(input.dataFormat{i+1},1) = repmat(input.dataFormat(i),length(input.dataFormat{i+1}),1);
end

Pablo

### Pablo (view profile)

Thanks for posting this code. Very useful!

Pablo

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

This update brings the option to pivot/transpose your table. It is now possible to define the data format (how your data is shown in LaTex) column- or row-wise.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

The function works row-wise so the format for each data row is the same. You could tweak the code in section '% generate row-format cell array based on input.tableDataFormat' and then apply the format in section '% make table rows:'. I'm planning to implement switching between row-wise and cloumn-wise tables in my next update.

Manuel

### Manuel (view profile)

Is it possible to change the format of each single column differently like changing the format of each row ?

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

By now the function only supports multi-row headers. I'm planning to rewrite the code in a way that the whole table can be pivoted between row-based and cloumn-based. This would also cover multi-line and multi-row headers.

Manuel

### Manuel (view profile)

And is it possible to support utf8 signs ?

Manuel

Manuel

### Manuel (view profile)

Thank you very much...It works very well. I expected this way to be the solution but didn't find the right way to code it. Is it also possible to have multicolumn headers ?

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Manuel, yes it is possible. The function gives back a cell array containing the lines of the LaTex code. You can loop through this cell array and print the lines to a text document. Try something like this:

myCellArray = latexTable(input);
fid = fopen('myLatexFile.tex', 'wt+')
for i = 1 : size(myCellArray,1)
fprintf(fid, '%d%d%s\t\n', myCellArray{i,:});
end
fclose(fid);

Manuel

### Manuel (view profile)

Is it possible to output the code direktly to a .tex document from the command window ?? If not, how can I realize ?

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

It is now possible to use the new MATLAB datatype 'table' as data input.

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Mehmet, it seems to me that your code is not providing the field input.tableData which contains the data that should be placed in a LaTex table. I just uploaded a script runExample.m that runs an example of how to use latexTable.m. Maybe you try to run this on your system and compare it with your code. Please let me know if the problem persists.

Mehmet Niyazi ÇANKAYA

### Mehmet Niyazi ÇANKAYA (view profile)

Hello,

Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release Notes, Assigning Nonstructure Variables As Structures
Displays Warning, for details.
> In latexTable at 65
Reference to non-existent field 'tableData'.

Pi Ting

useful

Eli Duenisch

### Eli Duenisch (view profile)

• 1 file
• 4.91304

Hi Timo, thank you for your feedback. I have been thinking about the support of MATLAB tables and I will implement it in the update (in a week or so).

Timo

### Timo (view profile)

Fantastic submission, Eli. A true time saver. Thanks! I am just getting to know the 2013b table function which so far looks really useful. Would it be possible to have latexTable accept a matlab table as an input? That would be amazing.

Chris

### Chris (view profile)

It does the job quick and simple.Great!