What is fprintf?

MATLAB’s fprintf command is a powerful command that can be used for different applications. In this course, we will use it to display text and variable information to the Command Window screen.

MATLAB documentation on using fprintf to display text to the screen is here.

MATLAB documentation on and conversion characters and special characters within fprintf is here.

Conversion Characters

A conversion character specifies the appearance of the output to the screen. This is most important in this course to properly display decimal values with an appropriate level of precision. The conversion character is is the only required field of the format specifier along with the leading % character. MATLAB has many conversion characters but all numeric displays in this course can be done using the f conversion character. You many also find the string conversion %s helpful if you display string variables using fprintf.

Example command window showing 
four different ways to display the variable tempvar. The variable is defined as tempvar = 174.23788663. The commands only show use of the %f conversion character inside the fprintf command. The first example uses just %f. This displays tempvar as 174.237887 degrees. The second example shows %0.2f. This displays tempvar as 174.24 degrees. The third example shows %.2f. This also displays tempvar as 174.24 degrees. The fourth display shows %.0f. This displays tempvar as 174 degrees.

Special Characters

You may want to display special characters that also have separate meaning within the fprintf command syntax. Note the '' to display a single apostrophe, %% to display a single percent symbol, and \n to move to a new line.

This image shows example code that allows you to display the apostrophe character, the percent sign, and how to make a new line. To display an apostrophe, use ''. To display a percent sign, use %%. To force a new line, use \n.