I need help with string formatting

조회 수: 6 (최근 30일)
Grzegorz Lippe
Grzegorz Lippe 2015년 7월 15일
답변: Guillaume 2015년 7월 15일
Hello,
I need a formatted string and came up with this:
colFormatWidth = [ 5 25 10 10 10 10 5 5 5 5 10 ] ;
colFormatType = {'d' 's' 'f' 'd' 'f' 'f' 'f' 'f' 'f' 'f' 'f' } ;
formatRowDummy = sprintf('%%%%%%d%s', colFormatType{:} ) ;
formatRow = sprintf(formatRowDummy, colFormatWidth)
>> formatRow
formatRow =
%5d%25s%10f%10d%10f%10f%5f%5f%5f%5f%10f
Is there a smarter way to do this?
PS Additionally it will get even more messy if I try to achive something like
%10.4f
with this approach.

답변 (1개)

Guillaume
Guillaume 2015년 7월 15일
I don't know about smarter, this is actually quite smart. I would just add a comment on the formatRowDummy line to explain the treble escaping of the % character (it has to survive going through two sprintf).
If the format string becomes even more complex, then probably the best thing is to revert to a loop (either explicit for or arrayfun) building each subpart of the format, with a final concatenation. It might be slower but the code would be clearer.
As it is:
formatrows = arrayfun(...
@(w, t) sprintf('%%%d%s', w, t{1}), ...
colFormatWidth, colFormatType, 'UniformOutput', false);
formatrow = [formatrows{:}]

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by