フィルターのクリア

How can I change where a variable is placed within the field width using fprintf?

4 ビュー (過去 30 日間)
Tanner Thorsen
Tanner Thorsen 2019 年 10 月 21 日
編集済み: Stephen23 2019 年 10 月 21 日
I am working with a function that specifies a field width of 20 characters for column labels.
for i=1:length(q.labels)
fprintf(fid, '%20s\t', q.labels{i});
end
The problem I am having, is that in the written file, the label is being printed to the last characters of the 20-character field width. So, for example, if my label is ‘DOG’, my column label has 17 blank spaces and then the word DOG. How can I fix this so that the label prints to the beginning of the field width?

採用された回答

Yuan Li
Yuan Li 2019 年 10 月 21 日
fprintf(fid,['%' num2str(length(q.labels{i})) 's\t'],q.labels{i});
change the code in the for loop will help you solve the problem.

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 10 月 21 日
編集済み: Stephen23 2019 年 10 月 21 日
By default the text will be right-justified within the field.
The fprintf documentation states that you can left-justify using the - character:
fprintf(fid, '%-20s\t', q.labels{i});
% ^ this is all you need
Note that the loop is not required:
fprintf(fid, '%-20s\t', q.labels{:});

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by