Skip to main content
v2026.11,986 entries · CC-BY 4.0

sprintf in MATLAB: Syntax, Format Specifiers and sprintf vs fprintf

MATLAB sprintf formats values into text and returns it. Syntax, format operators, examples, sprintf vs fprintf vs disp, and common pitfalls.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

MATLAB sprintf formats data into text and returns it as a value; it does not print anything. The syntax is str = sprintf(formatSpec,A1,...,An). Use it when you need the formatted result inside another call, such as a plot title, a file name, an error message or a log line. Use fprintf when you want the text written to the Command Window or a file. This page is for researchers and analysts who need to turn numbers into clean, reproducible text. Sources were read on 2026-11-08.

What sprintf is used for in research

sprintf is the “format first, use later” tool. Because the formatted text comes back as a variable, you can pass it to any function that takes text. Typical research uses:

  • Building file names for repeated runs, for example one output file per subject or parameter value.
  • Putting a rounded statistic into a figure title or axis label.
  • Composing a message for disp or error so that a result is reported with a fixed number of decimals.
  • Replacing ad hoc number-to-text conversion with explicit control of width and precision.

The format rules are the same as for fprintf. This page covers what is specific to sprintf; the full conversion and flag walkthrough is in fprintf in MATLAB.

Access: where sprintf is documented and available

sprintf is a MATLAB function documented in MathWorks’ MATLAB reference at mathworks.com/help/matlab/ref/sprintf.html. Open MATLAB and type help sprintf or doc sprintf to read the documentation that matches your installed release. GNU Octave, a free alternative, has its own sprintf; see the alternatives table below.

Step by step: format values into text

  1. Write a format specification. Each operator starts with % and ends with a conversion character. The identifier, flags, field width, precision and subtype are optional.
  2. Pick the conversion for each value. %d or %i for signed integers; %u, %o, %x, %X for unsigned integers; %f for fixed-point; %e or %E for exponential; %g or %G for the shorter of %e or %f without trailing zeros; %c for a single character; %s for a character vector or string.
  3. Call sprintf with the values after the format.
  4. Store or use the returned text.
subject = 7;
r = 0.83712;
name = sprintf('subject%02d_r%.3f.mat', subject, r);
% name is 'subject07_r0.837.mat'

ttl = sprintf('Correlation r = %.2f (n = %d)', r, 120);
% ttl is 'Correlation r = 0.84 (n = 120)'

Special characters inside the format: %% writes a literal percent sign, '' writes a single quote inside a single-quoted character vector, and escape sequences such as \n in formatSpec are translated into the corresponding character.

Output and how to read it

The output is one text value. Per the MathWorks documentation, if formatSpec is a string, then so is the output str; a character vector in gives a character vector out. When you pass an array, the format is applied to all elements in column order and reused until the data run out:

sprintf('%d, ', [1 2 3])
% ans = '1, 2, 3, '

Note the trailing separator: the format is applied once per element, so a separator inside formatSpec appears after the last value too. Trim it afterwards if it matters.

Reordering with the n$ identifier

An identifier of the form n$ selects the nth input, so you can reorder values without reordering the arguments. The documented example: with A1 = 'X', A2 = 'Y', A3 = 'Z' and formatSpec = ' %3$s %2$s %1$s', the result is ' Z Y X'.

Padding with zeros

The 0 flag pads with leading zeros. The documentation gives sprintf('%025d',123456) as producing 25 characters with leading zeros. Other flags are - (left-justify), + (always print a sign) and a space (insert a leading space for positive values).

sprintf vs fprintf vs disp

Function What it does with formatted text Use it when
sprintf Returns the formatted text as a value The text feeds another call: file names, titles, messages
fprintf Writes formatted data to the screen or a text file You want output printed or saved directly
disp with a sprintf result Displays a text value you already built You want a formatted number shown on its own line
compose Formats into a string array or cell array of pieces You need several formatted strings at once rather than one

The MathWorks sprintf documentation points to compose for formatting multiple pieces as a string array or cell array. For printing to a file or screen, see fprintf in MATLAB.

Troubleshooting

Why does %s print a number in exponential form?

If you apply %s to a numeric value, MathWorks documents that MATLAB overrides the conversion and uses %e. For example, %s applied to pi gives 3.141593e+00. Use %f, %g or %d for numbers, and %s only for text.

Why is my output cut off?

If the format contains an invalid operator, the documentation states that sprintf prints the text up to the invalid operator and discards the rest. A stray % in a message is the usual cause; write %% for a literal percent sign.

Why do I get a character vector when I expected a string?

The output type follows the format: a string format gives a string, a character-vector format gives a character vector. Pass the format as a string if you want a string result.

Free alternatives

Tool sprintf behavior Source
MATLAB str = sprintf(formatSpec,A1,...,An); returns formatted text MathWorks MATLAB reference, sprintf
GNU Octave Like printf, except that the output is returned as a string; the string is automatically sized, with no buffer to manage; escape sequences are expanded even in single-quoted templates GNU Octave manual, Formatted Output

If you share code between MATLAB and Octave, keep format strings simple and test the output in both. For broader MATLAB reading, see matrices in MATLAB and the MATLAB switch statement.

FAQ

What does sprintf do in MATLAB?

It formats data according to formatSpec and returns the result as text instead of printing it.

What is the difference between sprintf and fprintf in MATLAB?

sprintf returns the formatted text as a value; fprintf writes it to the screen or a file. Both use the same format operators.

How do I put a variable value in a string with sprintf?

Put a conversion such as %d or %.2f in the format and pass the variable after it: sprintf('n = %d', n).

How do I print a percent sign or a single quote?

Use %% for a percent sign and '' for a single quote in a single-quoted format.

Sources

  • MathWorks, MATLAB documentation: sprintf (read 2026-11-08).
  • MathWorks, MATLAB documentation: fprintf (read 2026-11-08).
  • GNU Octave manual: Formatted Output (read 2026-11-08).

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about sprintf in MATLAB: Syntax, Format Specifiers and sprintf vs fprintf

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →