How are fprintf column headers in MATLAB?
I have two matrices A and B as follows:
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 below form with the column headings 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 can I insert column headings as shown above using MATLAB? Sometimes the columns in B can be over 100, I only gave 4 as an example.
source to share
In my private collection of utility scripts, I have a function for "pretty-printable" 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 can 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 headers and columns only align well if the column labels are not too large, you may 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 '% .3f\t'
)
source to share