0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use fprintf in MATLAB: Syntax and Examples

In MATLAB, fprintf prints formatted text to the command window or a file. Use fprintf(fileID, formatSpec, A, ...) where fileID is the output destination, formatSpec defines the text format, and A are the values to print.
๐Ÿ“

Syntax

The basic syntax of fprintf is:

  • fprintf(formatSpec, A, ...): Prints formatted text to the command window.
  • fprintf(fileID, formatSpec, A, ...): Prints formatted text to a file identified by fileID.

formatSpec is a string that specifies how to format the output, using placeholders like %d for integers, %f for floating-point numbers, and %s for strings.

A, ... are the values to be printed, matching the placeholders in formatSpec.

matlab
fprintf(formatSpec, A, ...)
fprintf(fileID, formatSpec, A, ...)
๐Ÿ’ป

Example

This example shows how to print formatted text to the command window using fprintf. It prints a greeting with a name and a number with two decimal places.

matlab
name = 'Alice';
score = 95.6789;
fprintf('Hello, %s! Your score is %.2f.\n', name, score);
Output
Hello, Alice! Your score is 95.68.
โš ๏ธ

Common Pitfalls

Common mistakes when using fprintf include:

  • Not matching the number of placeholders in formatSpec with the number of variables provided.
  • Forgetting to include \n for a new line, causing output to run together.
  • Using the wrong placeholder type (e.g., %d for a floating-point number).
  • Not opening a file with fopen before writing to it.
matlab
fileID = fopen('output.txt', 'w');
% Wrong: missing newline and mismatched placeholders
fprintf(fileID, 'Value: %d %d', 3.14, 2);
% Correct:
fprintf(fileID, 'Value: %.2f\n', 3.14);
fclose(fileID);
๐Ÿ“Š

Quick Reference

PlaceholderDescriptionExample
%dInteger numberfprintf('%d', 10) prints 10
%fFloating-point numberfprintf('%.2f', 3.1415) prints 3.14
%sStringfprintf('%s', 'text') prints text
\nNew linefprintf('Line1\nLine2') prints two lines
%%Literal percent signfprintf('%%') prints %
โœ…

Key Takeaways

Use fprintf to print formatted text to the command window or files in MATLAB.
Match the number and type of placeholders in formatSpec with the variables provided.
Always include \n to move to a new line when printing multiple lines.
Open files with fopen before writing and close them with fclose after.
Use placeholders like %d, %f, and %s to format integers, floats, and strings.