putting space between string and double using fprintf

67 vues (au cours des 30 derniers jours)
sermet OGUTCU
sermet OGUTCU le 13 Août 2021
Modifié(e) : Adam Danz le 13 Août 2021
fprintf(fid,'%*s %*s\n',10,' G1',10,' G2');
fprintf(fid,'%s %.1f %s %.1f\n', 'Average_1:', data_1, 'Average_2:', data_2);
In the first code, 10 spaces were added before 'G1' and 'G2' string. In the second code, how I can add 10 spaces before "Average_1" and "Average_2"?

Réponse acceptée

Adam Danz
Adam Danz le 13 Août 2021
Modifié(e) : Adam Danz le 13 Août 2021
> In the first code, 10 spaces were added before 'G1'
That's incorrect. 8 spaces are added prior to 'G1'. From the documentation, the asterisk and number pair defines the minimum number of characters to print including the number of characters in the string. In this case, G1 contains 2 strings so there are 8 spaces added.
This solution uses an anonymous function addSpace(n,str) where n is a positive integer and str is a character row vector. Call the function within fprintf inputs to add n spaces prior to the string.
addSpace = @(n,str)[char(32*ones(1,n)),str];
fprintf('%s %.1f%s %.1f\n', ...
addSpace(10,'Average_1:'), rand, ...
addSpace(10,'Average_2:'), rand);
Average_1: 0.4 Average_2: 0.5

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by