Thursday, November 24, 2011

Using MATLAB to print a matrix in Latex

I came across a life-changing page a couple of days ago, while writing a report for my Visual Recognition class.

People who have tried reporting confusion matrices or comparative accuracy tables will understand that I am not exaggerating.

Assume you have a matrix M.
Then all you need to type is:

s = sym(M);
latex(vpa(s,3)); %Sets precision of elements to 3

MATLAB will print out the array in Latex!

If you want a tabular output of a matrix of values, here's a short python script I had written tired of trudging through endless &'s and \hline's. It can't handle missing data, so you need to give it a full matrix. The matrix is space-delimited and stored in a file (This is because I would just copy-paste the matrix from MATLAB into a txt file).


def createLatexTable(inputFile, rowHeaders=[], colHeaders=[], scale=0.8):
    f = open(inputFile)
    fLines = f.readlines()
    #To figure out number of columns
    dummyline = fLines[0].strip()
    numColumns = len(dummyline.split())

    print '\\scalebox{'+str(scale)+'}{'
    print '\\begin{tabular}{|',
    if len(rowHeaders) > 0:
        for i in range(numColumns+1): print 'c|',
    else:
        for i in range(numColumns): print 'c|',
    print '}'
    
    print '\\hline'    
    if(len(colHeaders) > 0):
        if len(rowHeaders) > 0:
            print ' & ',
        print ' & '.join(colHeaders),
        print '\\\\ \\hline'

    rowCount = -1
    for line in fLines:
        line = line.strip()
        nums = line.split()
        if len(nums)==0:
            continue
        rowCount = rowCount+1
        if len(rowHeaders) > 0: print rowHeaders[rowCount],' & ',
        print ' & '.join(nums),
        print '\\\\ \\hline' 
        
    print '\\end{tabular}'
    print '}'

    f.close()

3 comments:

  1. Hey thanks for the post......as of now I do not need to print out matrices.....but I may need it in future! :)!!

    Also by output in latex, you mean .tex and not .pdf right?

    ReplyDelete
  2. It's text you can directly paste into your .tex file

    ReplyDelete

Note: Only a member of this blog may post a comment.