Matlab

What are %f and %s in MATLAB?

In MATLAB, format specifiers are used with the fprintf command to control the appearance of output, and the two commonly used format specifiers are %f and %s. These specifiers are essential for formatting strings and floating-point numbers, respectively. This article aims to provide a clear understanding of %f and %s in MATLAB, along with example code to illustrate their usage.

The %f Format Specifier

The %f format specifier is used to display or write floating-point numbers with a fixed decimal format. It allows control over the precision of the displayed numbers. Here is some sample MATLAB code that shows how to use the %f format specifier:

x = 3.14159;

fprintf('The value of x is %0.2f\n', x);

In this code, the variable x is assigned the value of 3.14159. The fprintf command is then used to display x with a precision of two decimal places using the %0.2f format specifier. The output will be:


Here, %0.2f instructs MATLAB to display x as a floating-point number with two decimal places.

The %s Format Specifier

The %s format specifier is used to display or write strings in MATLAB, and is commonly used when working with character arrays or cell arrays of strings. Here’s an example code that illustrates the usage of the %s format specifier:

name = 'Sam';

fprintf('Hello, %s!\n', name);

In this code, the variable name is assigned the string Sam and using the fprintf command with the %S format specifier, we can display the value of ‘name’ as part of a formatted string. The output will be:

A screenshot of a computer Description automatically generated with low confidence

Here, %s instructs MATLAB to treat the argument name as a string and include it in the output, as is in the image above.

Note: Using an incorrect format specifier will give imprecise or wrong output. For example, if we use the %f specifier with a string the output will be:

The %f specifier is giving the ASCII values of S, a, and m. To learn more about ASCII click here.

Conclusion

The %f and %s format specifiers in MATLAB play a crucial role in formatting floating-point numbers and strings, respectively. By incorporating these format specifiers into the fprintf command, users can effectively present numerical and textual data in a desired format.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.