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 byfileID.
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
formatSpecwith the number of variables provided. - Forgetting to include
\nfor a new line, causing output to run together. - Using the wrong placeholder type (e.g.,
%dfor a floating-point number). - Not opening a file with
fopenbefore 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
| Placeholder | Description | Example |
|---|---|---|
| %d | Integer number | fprintf('%d', 10) prints 10 |
| %f | Floating-point number | fprintf('%.2f', 3.1415) prints 3.14 |
| %s | String | fprintf('%s', 'text') prints text |
| \n | New line | fprintf('Line1\nLine2') prints two lines |
| %% | Literal percent sign | fprintf('%%') 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.