Number of leading zeroes as a variable

16 ビュー (過去 30 日間)
James
James 2016 年 10 月 24 日
回答済み: Honglei Chen 2016 年 10 月 24 日
I know that to print out a number with a certain amount of leading zeroes, you are supposed to use %0X, where X is the number of digits you want in your output. For example, sprintf('%06g',13) gives you the string '000013' as output. Is there a way to make the formatting value a variable? Something along the lines of
function x=leadzero(y,z)
x=sprintf('%0y',z)
end
I know it can be done with a for loop, but is there are way to implement this directly into the sprintf command?

採用された回答

dpb
dpb 2016 年 10 月 24 日
Fer shure, just write the format string desired dynamically--
function s=leadzero(Nz,z)
fmt=num2str(Nz,'%%0%dg');
s=sprintf(fmt,z)
end
Nz for "Number zeros" seemed a better variable name than y as did an s for a returned string output variable...the format string expression can be wrapped inside the sprintf call, of course, just wrote it out for clarity here.

その他の回答 (1 件)

Honglei Chen
Honglei Chen 2016 年 10 月 24 日
y = 6;
z = 13;
sprintf(['%0' num2str(y) 'g'],z)

カテゴリ

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