putting space between string and double using fprintf
47 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam Danz
2021-8-13
编辑:Adam Danz
2021-8-13
> 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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!