matlabmatlab-table

Is there a way to create a table with multi-line column names?


I am attempting to create a table that has the following format of multi line heading for the columns

|Col1 Co2 Col3|

|Col1 Co2 Col3|

Tried this using the example and adding a | between 1st and 2nd line but did not work

T = table(categorical({'M';'F';'M'}),[45;32;34],...

      {'NY';'CA';'MA'},logical([1;0;0]),..

      'VariableNames',{'Gender|Gender2','Age|Age2','State|State2','Vote|Vote2'})

I am using R2018b student edition


Solution

  • The ability to have arbitrary variable names in tables was added to release R2019b of MATLAB. Using that release, your code works as expected and produces:

    T =
      3×4 table
        Gender|Gender2    Age|Age2    State|State2    Vote|Vote2
        ______________    ________    ____________    __________
              M              45          {'NY'}         true    
              F              32          {'CA'}         false   
              M              34          {'MA'}         false   
    

    However, in your question you state that you want multi-line variables. You can make these in R2019b, but the display collapses the newline character into a , like this:

    >> T = table(1, 'VariableNames', {['a', newline, 'b']})
    T =
      table
        a↵b
        ___
         1 
    

    If it's just the display you're after, you could consider making nested tables, like this:

    t1 = table(1);
    t2 = table(2);
    T = table(t1, t2)
    

    which results in:

    T =
      1×2 table
         t1      t2 
        Var1    Var1
        ____    ____
         1       2  
    

    Note that that final approach works in R2019a and prior releases.