Printing a cell array of strings and numbers with fprintf?

192 views (last 30 days)
I am trying to print the cell array C=
'Andie,A.' 'a5123' [85] [100] [90] [91.6667]
'Ellen,E.' 'e1567' [86] [ 88] [89] [87.6667]
'Francine,F.' 'f2321' [85] [ 87] [90] [87.3333]
'George,G.' 'g3455' [70] [ 65] [72] [ 69]
'Ike,I.' 'i4678' [68] [ 45] [92] [68.3333]
'Madeleine,M.' 'm2134' [55] [ 47] [59] [53.6667]
'Tabitha,T.' 't5321' [20] [ 58] [65] [47.6667]
This is my code
for i=1:7
for j=1:6
fprintf(fpd,'%s %s %d %d %d %3.2f\t',C{i,j});
end;
fprintf(fpd,'\n');
end;
However it doesn't print the integers as integers, rather it converts them to ASCII and I end up with a table of letters instead of the numbers I want. Any ideas of what is wrong? Thanks Matt

Accepted Answer

Stephen23
Stephen23 on 29 Oct 2015
Edited: Stephen23 on 29 Oct 2015
There is no need for the loops, just transpose the cell array and then use {:} to convert it to a comma separated list. fprintf repeatedly applies the format string to all of the input arguments, so it does the looping for you!
D = C';
fprintf('%s %s %d %d %d %3.2f\n',D{:})
and it prints this text in the command window:
Andie,A. a5123 85 100 90 91.67
Ellen,E. e1567 86 88 89 87.67
Francine,F. f2321 85 87 90 87.33
George,G. g3455 70 65 72 69.00
Ike,I. i4678 68 45 92 68.33
Madeleine,M. m2134 55 47 59 53.67
Tabitha,T. t5321 20 58 65 47.67
We can also align the columns:
D = C';
D(2:end+1,:) = D;
D(1,:) = {max(cellfun('length',C(:,1)))};
fprintf('%*s %3s %3d %3d %3d %3.2f\n',D{:})
to create this:
Andie,A. a5123 85 100 90 91.67
Ellen,E. e1567 86 88 89 87.67
Francine,F. f2321 85 87 90 87.33
George,G. g3455 70 65 72 69.00
Ike,I. i4678 68 45 92 68.33
Madeleine,M. m2134 55 47 59 53.67
Tabitha,T. t5321 20 58 65 47.67

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!