putting space between string and double using fprintf
48 views (last 30 days)
Show older comments
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"?
0 Comments
Accepted Answer
Adam Danz
on 13 Aug 2021
Edited: Adam Danz
on 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);
0 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!