putting space between string and double using fprintf

조회 수: 42 (최근 30일)
sermet OGUTCU
sermet OGUTCU 2021년 8월 13일
편집: Adam Danz 2021년 8월 13일
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"?

채택된 답변

Adam Danz
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);
Average_1: 0.4 Average_2: 0.5

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by