vertical alignment with different size character with fprintf.

15 visualizaciones (últimos 30 días)
sermet
sermet el 26 de Abr. de 2015
Editada: Stephen23 el 26 de Abr. de 2015
C = {'p.1001',100.500,250.350,;'102',110.550,255.220;'m285',115.210,266.333};
fileID = fopen('celldata.dat','w');
formatSpec = '%s %15.3f %15.3f\n';
[nrows,ncols] = size(C);
for row = 1:nrows
fprintf(fileID,formatSpec,C{row,:});
end
fclose(fileID);
% in this case second and third columns cannot be vertically aligned in the text file because first columns' characters are different size. When I use tab (/t), the situation is still same. Is there any way to vertically align 2rd and 3rd columns as independently the 1st columns' characters size?
  1 comentario
Stephen23
Stephen23 el 26 de Abr. de 2015
Presumably you mean "horizontal alignment" in the title, rather than "vertical alignment".

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 26 de Abr. de 2015
Editada: Stephen23 el 26 de Abr. de 2015
According to the fprintf documentation one can specify a field width for character substring:
>> fprintf('%s\n','cat')
cat
>> fprintf('%8s\n','cat')
cat
So simply changing the format string to this will allign all of the columns:
>> formatSpec = '%6s %15.3f %15.3f\n';
If the maximum string width is not known, then you can generate this from the substrings themselves:
>> X = max(cellfun('length',C(:,1)));
>> formatSpec = sprintf('%%%ds %%15.3f %%15.3f\n',X);
Or use this value directly using the * notation:
>> X = max(cellfun('length',C(:,1)));
>> formatSpec = '%*s %15.3f %15.3f\n';
and then
fprintf(fileID, formatSpec, X, C{row,:});

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by