Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

fprintf in MATLAB: formatSpec, Matrix, Newline and %e

fprintf in MATLAB explained: a formatSpec table, new lines, scientific notation, and why a matrix prints in column order.

Written and maintained by CASRAI Editorial Board

Last updated

Reader task: you need to print numbers or text from MATLAB in an exact layout, to the screen or to a file, and understand why a matrix prints in an unexpected order. fprintf writes formatted data using a format specification (formatSpec); with no file identifier it prints to the screen.

What fprintf is used for in research

fprintf(formatSpec, A1, ..., An) formats the values A1 to An and displays them on screen. fprintf(fileID, formatSpec, A1, ..., An) writes them to a file. nbytes = fprintf(___) also returns the number of bytes written. In analysis work it is the usual way to print a labelled result line, a fixed-precision table row, or a tab-delimited text file whose layout a collaborator or downstream tool expects. For simpler display, see the broader print in MATLAB guide, which covers disp and tables.

Install or access

fprintf is a built-in MATLAB function, so nothing beyond MATLAB itself is needed. The reference page is MathWorks’ fprintf documentation. GNU Octave, a free alternative, documents printf, fprintf and sprintf in its formatted output chapter.

Step by step: build a formatSpec

  1. Choose where the output goes. Omit fileID to print to the screen. fileID defaults to 1 (standard output); 2 is standard error.
  2. Write the formatSpec as text with conversions. Each conversion starts with %. Example: fprintf('Mean = %.4f\n', pi) prints Mean = 3.1416 followed by a new line.
  3. Set width, precision and flags where needed. Width is the minimum number of characters (a number, or *). Precision is the number of digits after the decimal point for %f, %e and %E, and the number of significant digits for %g and %G.
  4. Add the values. One argument per conversion, in order; the n$ identifier lets you set the argument processing order explicitly.
  5. End each line with \n. Put the escape in the formatSpec to start a new line.

formatSpec reference table

All rows below come from the MathWorks fprintf reference page (read 2026-11-07).

Element Meaning
%d, %i Signed integer
%u Unsigned integer
%o Octal
%x, %X Hexadecimal
%f Fixed-point notation
%e, %E Exponential notation, for example 3.141593e+00
%g, %G The more compact of %e or %f, with no trailing zeros
%c Single character
%s Character vector or string array
flag - Left-justify
flag + Always print a sign
flag (space) Insert a space before the value
flag 0 Pad with zeros
flag # Modifies o, x, X (prefix), f, e, E (decimal point) and g, G (keeps trailing zeros)
\n, \r, \t New line, carriage return, tab
%% A literal percent sign
'' A literal single quote

Output and how to read it

fprintf in MATLAB with a new line

Use \n in the formatSpec. fprintf('a\nb\n') prints a and b on separate lines. Use \t for a tab between columns.

MATLAB fprintf scientific notation

Use %e for exponential form, or %g when you want whichever of exponential and fixed notation is more compact. Per the documentation, pi in %e appears as 3.141593e+00, and '%.4f' prints it as 3.1416.

MATLAB fprintf matrix: column order

MathWorks documents that fprintf applies the formatSpec to all elements of the arrays in column order. For a matrix M = [1 2; 3 4] the element sequence is therefore 1, 3, 2, 4 (the columns read top to bottom). So fprintf('%d %d\n', M) prints 1 3 then 2 4, which looks transposed. Printing M.' instead gives one matrix row per line (derived from the documented column order; try it on a small matrix to confirm in your release). For background on building and transposing matrices, see matrix in MATLAB.

How to print an array in MATLAB using fprintf: pairing two vectors

A MATLAB Answers thread (accepted answer by Honglei Chen, read 2026-11-07) shows the idiom for printing two vectors side by side: with a = 1:5 and b = 90:94, fprintf('Variables A : %.f | Variables B : %.f\n', [a; b]) prints one pair per line, because stacking the vectors as rows makes column order interleave them. For column vectors, a reply in the thread suggests [a, b].'.

Worked example: a results row

fprintf('%s: n = %d, mean = %.2f\n', 'Group A', 24, 3.14159)

The conversions consume the arguments in order: %s takes the text, %d the integer, %.2f the number with two digits after the decimal point, giving Group A: n = 24, mean = 3.14 (derived from the documented rules). Precision here controls display of the value in the output text. For rounding stored values in another tool, see rounding in R.

fprintf vs disp vs sprintf

  • disp shows a value with MATLAB’s default formatting and no formatSpec; fprintf gives you control of the layout.
  • sprintf is listed under See Also on the fprintf page and uses the same style of format specification.
  • The reading functions sscanf and fscanf use format specs that differ from the output functions; for example they have no precision field.

Troubleshooting

  • Percent sign missing: write %%.
  • Output stops partway through the text: per the documentation, an invalid conversion operator or special character makes MATLAB print the text up to that point and discard the rest. Check for a stray % or \.
  • Unexpected number format with %s: if the value does not match the conversion, MATLAB may override it. The documentation’s example is %s with pi, which prints 3.141593e+00; %s with [65 66 67] prints ABC.
  • Values appear in the wrong order for a matrix: see the column-order section above; stack or transpose the data.
  • Data held in a cell array: see MATLAB cell arrays for how to index values out before printing.

Free alternatives

Tool Equivalent Note (source read 2026-11-07)
GNU Octave fprintf (fid, template, ...), printf, sprintf Documented in the Octave manual’s Formatted Output chapter. For matrices, Octave cycles through the template until all values are printed and does not return to the start of the template between values; its manual warns this can give confusing output when the number of elements is not an exact multiple of the number of conversions.

FAQ

What is formatSpec in MATLAB?

It is the text template passed to fprintf that mixes literal text with conversions such as %d, %f and %s, plus optional flags, width and precision.

How do I print a new line with fprintf?

Add \n to the formatSpec.

How do I print a percent sign?

Use %%.

What does fileID 1 mean?

1 is standard output (the screen), the default; 2 is standard error.

Does fprintf return anything?

With nbytes = fprintf(___) it returns the number of bytes written.

Sources

Follow CASRAI

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

Ask CASRAI · free to try

Ask about fprintf in MATLAB: formatSpec, Matrix, Newline and %e

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

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 free 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 →