putting space between string and double using fprintf

41 Ansichten (letzte 30 Tage)
sermet OGUTCU
sermet OGUTCU am 13 Aug. 2021
Bearbeitet: Adam Danz am 13 Aug. 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"?

Akzeptierte Antwort

Adam Danz
Adam Danz am 13 Aug. 2021
Bearbeitet: Adam Danz am 13 Aug. 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

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by