We would like to write a script that prints a vector Vi one element per line (i.e. a new line is following every element), with 2 digits following the decimal point, and 8 digits in all. Every number is followed by a comma (,) except the last. In other words every number printed (other than the last) will be followed by a comma and then a new line. Which of the below codes can do that? a.l = length(Vi); fprintf('%.82f,\n',Vi(1:l-1)); fprintf('%6.2f\n',Vi(l)); b.l = length(Vi); fprintf('%8f,\n',Vi(1:l-1)); fprintf('%.2f\n',Vi(l)); c.l = length(Vi); fprintf('%8.2f,\n',Vi(1:l)); d.l = length(Vi); fprintf('%8.2f,\n',Vi(1:l-1)); fprintf('%8.2f\n',Vi(l));
We would like to write a script that prints a vector Vi one element per line (i.e. a new line is following every element), with 2 digits following the decimal point, and 8 digits in all. Every number is followed by a comma (,) except the last. In other words every number printed (other than the last) will be followed by a comma and then a new line. Which of the below codes can do that?
fprintf('%.82f,\n',Vi(1:l-1));
fprintf('%6.2f\n',Vi(l));
fprintf('%8f,\n',Vi(1:l-1));
fprintf('%.2f\n',Vi(l));
fprintf('%8.2f,\n',Vi(1:l));
fprintf('%8.2f,\n',Vi(1:l-1));
fprintf('%8.2f\n',Vi(l));
The "I = " just gets prints as-is. It's nothing special and any characters like that, that aren't preceded with a \ or a % just go down exactly as you put them. The % means it's going to replace that part of the string with a variable. The f means a floating point variable. An s means a string, and a d means an integer. So %f means it's going to replace the %f with the value of "I", out to 6 or 7 decimal places, because x is the variable that shows up after the 'I = %f\n' formatting string.
If you wanted a specific number of decimal places you could use %.3f to have 3 decimal places. If you wanted to pad spaces on the right to make the whole field, say, 20 characters wide, then you could use %20.3f which would put 3 decimal places to the right of the decimal point, however many digits it needs to the left of the decimal point, and then pad as many spaces on the left as it takes to make the whole thing 20 characters wide.
Step by step
Solved in 2 steps