sprintf inputs

조회 수: 12 (최근 30일)
joseph Frank
joseph Frank 2011년 7월 14일
Hi,
I am writing a function to determine the shape of a table I want to obtain where one of the inputs in the function is n,which specifies the number of decimal points that I want to have in the function: if in this function I am using: Table1{1,2}=sprintf('%.4f',s.beta(1,1)) to get 4 decimal points in the table, how can i replace the 4f by nf if my n=4,which enables me to play with the table later on if i want to change the number of decimal points for example to n=3;

채택된 답변

Walter Roberson
Walter Roberson 2011년 7월 14일
sprintf('%.*f',n,s,n,beta(1,1))
Notice that the field width is replaced each time the format string is passed through, with it being passed through multiple times if there are more items to output than there are format specifiers.
Alternately,
fmt = sprintf('%%.%df', n);
sprintf(fmt, s, beta(1,1));
  댓글 수: 2
Nathan Greco
Nathan Greco 2011년 7월 14일
Note that it's s.beta(1,1), not s, beta(1,1).
One could just as easily do
fmt = ['%.' num2str(n) 'f'];
sprintf(fmt, s.beta(1,1));
Walter Roberson
Walter Roberson 2011년 7월 15일
Ah, I didn't look closely enough. In that case the code would be
sprintf('%.*f', n, s.beta(1,1))
num2str() has a lot of overhead compared to sprintf()

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by