3

I have two matrices A and B as given below:

A = [1
     2
     3
     4
     5]

B = [10  11  12  13
     15  16  17  18
     17  12  15  13
     20  21  22  17
     40  41  32  33]

and I would like to output it to a text file in the form given below with column headers as shown:

Desired text output

A  B   B   B   B
1  10  11  12  13
2  15  16  17  18
3  17  12  15  13
4  20  21  22  17
5  40  41  32  33

Reproducible code

A = [1; 2; 3; 4; 5];
B = [10, 11, 12, 13;
     15, 16, 17, 18;
     17, 12, 15, 13;
     20, 21, 22, 17;
     40, 41, 32, 33;];

ALL = [A B];

ALL_cell = mat2cell(ALL, ones(size(ALL,1),1), size(ALL,2));

fID = fopen('output.dat','w');
f = @(x) fprintf(fID,'%s\n',sprintf('%f\t',x));
cellfun(f,ALL_cell);
fclose(fID);

How to insert the column headers as shown above with MATLAB? Sometimes, the columns in B could be over 100, as an example I have given only 4.

Tom Kurushingal
  • 6,086
  • 20
  • 54
  • 86
  • So by column headers you just want the name of the variable (i.e. `B`) repeated over every column? Just `fprintf(fID,'%s\n',sprintf('%s\t',['A',repmat('B',size(1,size(B,2)))]))`? – Dan Jun 12 '15 at 14:08
  • 1
    Do you have at least MATLAB R2013b? Using the `table` functions and its ilk will prove to be very useful. Let me know if you do, I'll write an answer. – rayryeng Jun 12 '15 at 15:57
  • @rayryeng I use R2012b. – Tom Kurushingal Jun 12 '15 at 16:30
  • Also, here: http://stackoverflow.com/questions/25397894/how-to-use-tables-in-older-versions-of-matlab – Marc Feb 01 '16 at 02:47

1 Answers1

1

In my private collection of utility scripts, I have a function to 'pretty-print' matrices:

function pprint(fid, M, cols)

fprintf(fid, '%s\t', cols{:});
fprintf(fid, '\n');
for irow=1:size(M, 1)
    fprintf(fid, '% .3f\t', M(irow,:));
    fprintf(fid, '\n');
end

You could use it like this:

>> headers = [repmat({'A'}, 1, size(A, 2)), repmat({'B'}, 1, size(B, 2))]

headers = 

    'A'    'B'    'B'    'B'    'B'

>> fid = 1; % print to stdout
>> pprint(fid, [A, B], headers)
A       B       B       B       B   
 1.000   10.000  11.000  12.000  13.000 
 2.000   15.000  16.000  17.000  18.000 
 3.000   17.000  12.000  15.000  13.000 
 4.000   20.000  21.000  22.000  17.000 
 5.000   40.000  41.000  32.000  33.000 

Note that the headers and the columns only line up nicely if the column labels are not too large, you might have to play with adding extra tabs, or use spaces instead of tabs (i.e. use '%10s' instead of '%s\t', and '%10.3f' instead of '% .3f\t')

Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62