How to format the length of a line of text using fprintf in a loop

11 vues (au cours des 30 derniers jours)
David Low
David Low le 7 Fév 2019
I am using MATLAB R2018a trying to print a text file using the following script which uses fprintf in a for loop. It prints the text file data corretly however I need the text to be right justified as can be seen in lines 1-13 of the second picture, however, lines 14-24 are indented to the left due to the length of "timestr" changing. I have tried adding '%42f' before X in my loop to set the line length to 42 characters but it did not work. Any help would be appreciated.
script.PNG
file.PNG
  2 commentaires
madhan ravi
madhan ravi le 7 Fév 2019
uploading a picture is less useful than providing the code
David Low
David Low le 7 Fév 2019
This is the code:
case_id=1
case_idstr=num2str(case_id);
metabol=strcat(' 1.40');
time=-60;
timestr=num2str(time);
X=strcat(timestr,' 24.6 23.30 0.070 49.90',metabol,'\n');
fid = fopen(strcat('bcfile',case_idstr,'.txt'),'wt');
fprintf(fid,' time Ta Twall va rh activ\n');
fprintf(fid,' [min] [øC] [øC] [m/s] [ ] [met]\n');
for loop=1:73
fprintf(fid,' ');
fprintf(fid,X);
time=time+5;
timestr=num2str(time);
X=strcat(timestr,' 24.6 23.30 0.070 49.90',metabol,'\n');
end
fclose(fid);

Connectez-vous pour commenter.

Réponses (1)

Jos (10584)
Jos (10584) le 7 Fév 2019
Why don't you format the values within each string to be nicely aligned, before sending them to a text file?
A = rand(4,3) ;
for k=1:size(A,1)
str = sprintf('%8.3f', A(k,:)) ;
fprintf('%s\n', str)
end

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by