Printing a cell array of strings and numbers with fprintf?

60 vues (au cours des 30 derniers jours)
Matt O'Dowd
Matt O'Dowd le 29 Oct 2015
Commenté : Matt O'Dowd le 29 Oct 2015
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

Réponse acceptée

Stephen23
Stephen23 le 29 Oct 2015
Modifié(e) : Stephen23 le 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

Plus de réponses (0)

Catégories

En savoir plus sur Performance and Memory dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by