0
0
MATLABdata~5 mins

String formatting (sprintf) in MATLAB

Choose your learning style9 modes available
Introduction
String formatting helps you create text with numbers or words arranged neatly. It makes your output clear and easy to read.
When you want to show numbers with a fixed number of decimal places.
When you need to combine text and numbers in one message.
When you want to create a formatted report or label.
When you want to prepare data for saving or printing in a specific style.
Syntax
MATLAB
str = sprintf(formatSpec, A, ...)
formatSpec is a string that tells how to format the data, like '%d' for integers or '%0.2f' for floats with 2 decimals.
A, ... are the values you want to insert into the format string.
Examples
Inserts the word 'world' into the text.
MATLAB
str = sprintf('Hello %s!', 'world')
Formats the number 42 as an integer.
MATLAB
str = sprintf('Value: %d', 42)
Shows the number with 2 decimal places.
MATLAB
str = sprintf('Pi approx: %.2f', 3.14159)
Formats two numbers with 1 decimal place each.
MATLAB
str = sprintf('Coordinates: (%.1f, %.1f)', 3.5, 7.2)
Sample Program
This program creates a formatted string with a name, age, and height, then shows it.
MATLAB
name = 'Alice';
age = 30;
height = 1.68;

info = sprintf('Name: %s\nAge: %d years\nHeight: %.2f meters', name, age, height);

disp(info)
OutputSuccess
Important Notes
Use %% in the format string to print a percent sign.
If you give fewer values than format specifiers, MATLAB will give an error.
You can format strings, integers, floats, and more using different codes like %s, %d, %f.
Summary
sprintf creates formatted text by inserting values into a template string.
Use format specifiers like %s for strings, %d for integers, and %f for floating-point numbers.
It helps make output clear and nicely arranged.