MATLAB:LaTeX Table Writer

From PrattWiki
Revision as of 22:35, 17 September 2011 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

Sometimes you will need to take data from a MATLAB script or function and present it using a LaTeX table. Rather than hand-code all the numbers, you may want to write a MATLAB loop to take care of producing the LaTeX code.

Create the Matrices

Probably the easiest way to create the table is to make sure all the information you want is stored in 1-D matrices (either columns or rows). Then you can just run a for loop with an indexing variable to pull out the appropriate values. For example if you want a table with temperatures in different units, you could start with:

TC = [-273.15 -40 0 100]';
TK = TC + 273.15;
TF = (TC+40)*9/5-40;
TR = TF + 459.67;

Generate LaTeX Code

Keep in mind for LaTeX tables, the entries are separated by & and the rows are terminated with \\. In MATLAB, to print a \, you must actually use the backslash command, which is \\. To get MATLAB to go to the next line, you need to use the \n command.

The following loop might be used to create the main parts of the LaTeX table for the matrices above:

for k=1:length(TC)
    fprintf('%8.2f & %8.2f & %8.2f & %8.2f \\\\ \n', TC(k), TK(k), TF(k), TR(k))
end

The output from this code is:

-273.15 &     0.00 &  -459.67 &     0.00 \\
 -40.00 &   233.15 &   -40.00 &   419.67 \\
   0.00 &   273.15 &    32.00 &   491.67 \\
 100.00 &   373.15 &   212.00 &   671.67 \\


Extra Code

Horizontal Lines

If you want horizontal lines between rows, LaTeX needs the \hline command after the double-slashes. Keeping in mind that MATLAB needs to \ two produce a \, you can write

for k=1:size(MainMat, 1)
    fprintf('%8.2f & %8.2f & %8.2f & %8.2f \\\\ \\hline \n', MainMat(k,:))
end

to get:

-273.15 &     0.00 &  -459.67 &     0.00 \\ \hline
 -40.00 &   233.15 &   -40.00 &   419.67 \\ \hline
   0.00 &   273.15 &    32.00 &   491.67 \\ \hline
 100.00 &   373.15 &   212.00 &   671.67 \\ \hline

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References