Find a Guide

MATLAB fprintf() Function

How fprintf() Works

Another way to print to MATLAB's Command Window is by using the 'fprintf()' function. Unlike the 'disp()' function, 'fprintf()' can allow for more formatting. The way 'fprintf()' works is a string is written, but identifiers are added to point where different variable's values should go. Let's take a look at the identifiers we can use.

  • %d or %i - signed integer, base 10
  • %u - unsigned integer, base 10
  • %o - unsigned integer, base 8
  • %x - unsigned integer, base 16 (lowercase letters, a-f)
  • %X - unsigned integer, base 16 (uppercase letters, A-F)
  • %f - floating-point number, fixed-point notation
  • %e - floating-point number, exponential notation (ex, 3.14159e+00)
  • %E - floating-point number, exponential notation (ex, 3.14159E+00)
  • %g - floating-point number, more compact %e or %f with no trailing zeros
  • %G - floating-point number, more compact %E or %f with no trailing zeros
  • %c - single chartacter
  • %s - character vector or string array

There are certainly a lot of different features, and there are more, but we will take things one step at a time. They will become fluent the more they are used! Let's take a look at a use.

matlab

age = 18;
name = "Steve";

fprintf("Today, %s is %i", name, age); % output: "Today, Steve is 18"

Rounding Numbers

We can do even more formatting with the 'fprintf()' function by rounding numbers. Let's take a look.

matlab

age = 18.9324;
name = "Steve";

fprintf("Today, %s turned %5.2d", name, age);
% output: "Today, Steve turned 1.89e+01"

Now we can print our data to the Command Window; this will make verification and communicating with the user much easier!

Find a Guide