MATLAB: Using a variable as the number of decimals in fprintf

fprintfvariable precision

Hi, I need to write a piece of code wherein the user specifies the amount of decimals fprintf should print when printing a certain matrix (infotable).
This is what I have:
—-
p = input('Please give the value of p (p = 0 --> no infotable is printed. p>0: infotable is printed with p decimals')
if p>0
fprintf('Iter. x f(x)\n');
fprintf('%0i %0.1f %0.1f\n',infotable')
It prints a table with the last two columns with one decimal. However, instead of the 1 before the f it should use the user-defined p. I tried inserting p in different ways, help much appreciated.
Thanks,
Casper

Best Answer

You need to convert "p" to a string, and insert it. (Notice that you also need to concatenate now, because it is not all one string.)
p = input('Please give the value of p (p = 0 --> no infotable is printed. p>0: infotable is printed with p decimals')
if p>0
fprintf('Iter. x f(x)\n');
fprintf(['%0i %0.',num2str(p),'f %0.',num2str(p),'f\n'],infotable')
end
Related Question