MATLAB: Sprintf inputs

sprintfvariable precision

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;

Best Answer

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));