Search code examples
matlabmatrixcell-array

How to fill up line with delimiters in Matlab


I have a cell array A, which I wish to print as a table. The first columns and first row are headers. For example I have

 A:
 1     2     3
 4     5     6
 7     8     9

And I want the output to look like this:

 A:
 1   ||2    |3
 -------------
 4   ||5    |6
 7   ||8    |9

The vertical bars are not problematic. I just dont know how to print out the horizontal line. It should be more flexible then just disp('-------'). It should resize depending on how big my strings in my cells are.

So far I only implemented the ugly way which just displays a static string '-----'.

function [] = dispTable(table)
basicStr = '%s\t| ';
fmt = strcat('%s\t||',repmat(basicStr,1,size(table,2)-1),'\n');
lineHeader = '------';
%print first line as header:
fprintf(1,fmt,table{1,:});
disp(lineHeader);
fprintf(1,fmt,table{2:end,:});
end

Any help is appreciated. Thanks!


Solution

  • You are not going to reliably be able to compute the width of a field since you are using tabs whose width can vary from machine to machine. Also if you're trying to display something in a tabular structure, it's best to avoid tabs just in case two values are different by more than 8 characters which would lead to the columns not lining up.

    Rather than using tabs, I would use fixed-width fields for your data, then you know exactly how many - characters to use.

    % Construct a format string using fixed-width fonts
    % NOTE: You could compute the needed width dynamically based on input
    format = ['%-4s||', repmat('%-4s|', 1, size(table, 2) - 1)];
    
    % Replace the last | with a newline
    format(end) = char(10);
    
    % You can compute how many hypens you need to span your data
    h_line = [repmat('-', [1, 5 * size(table, 2)]), 10];
    
    % Now print the result
    fprintf(format, table{1,:})
    fprintf(h_line)
    fprintf(format, table{2:end,:})
    
    %    1   ||2   |3
    %    ---------------
    %    4   ||7   |5
    %    8   ||6   |9