8.3. Converting Between Data Types and Strings
Table of Contents
Why Converting To and From Strings Matters
In MATLAB you often need to move between numeric data, text, and other data types. For example, you may want to create labels for plots that show numeric values, build filenames that contain numbers, or read numeric values that were originally stored as text in a file. This chapter focuses on how to convert different MATLAB data types to strings and how to go from strings back to other data types when needed.
Converting between types is especially important when you work with string arrays, character arrays, and data import or export. You will often read data as text and then convert parts of it to numbers, or you will generate text output from numeric results.
Converting Numbers to Strings
The most common conversion is from numbers to strings. In MATLAB there are several functions that can do this, but the modern and recommended ones work directly with string arrays.
The basic function is string. If you pass numeric data to string, MATLAB returns a string array with the same size, where each element is the text representation of the corresponding number. For example, the command
x = [3.14 42 -7];
s = string(x);
creates s as a 1 by 3 string array whose elements are "3.14", "42", and "-7".
If you want to control the numeric format, such as the number of decimal places, use compose. The general pattern is
s = compose(formatPattern, values);
Here formatPattern is a string that describes how each value should appear. For example,
x = [3.14159 2];
s = compose("%.2f", x);
creates a string array with "3.14" and "2.00". The pattern "%.2f" means a fixed point number with two digits after the decimal point.
When you want to convert numbers to characters rather than strings, use num2str. This function returns a character array, not a string array. For instance,
c = num2str(123.456);
produces a row vector of characters such as '123.456'. num2str lets you specify a precision too:
c = num2str(123.456, 4);
which keeps roughly 4 significant digits. Use num2str mainly when you need a character array for compatibility with older code.
Converting Strings to Numbers
The reverse operation converts text that looks like a number into real numeric values. This is very frequent after reading data from text files, user input, or spreadsheets.
For string arrays the main function is str2double. If you pass a string array or a character array, MATLAB tries to interpret each element as a number. For example,
s = ["3.14" "NaN" "42"];
x = str2double(s);
gives a numeric vector x that contains 3.14, NaN, and 42. If a string cannot be interpreted as a number, str2double returns NaN for that element. This behavior lets you detect invalid numeric entries.
Another function is str2num, which is more flexible but also more complicated. It can interpret expressions that contain spaces or multiple numbers in one string, such as "1 2 3". For example,
v = str2num("1 2 3");
returns a numeric row vector with three elements. However, str2num evaluates the content of the string as if it were MATLAB code, which is slower and can be unsafe for untrusted input. Prefer str2double when possible, especially for simple numeric text.
When dealing with integer types or logical values, you can combine str2double with type conversion. For instance,
s = "1";
n = uint8(str2double(s));
converts the string "1" first to the double 1, then to an 8 bit unsigned integer.
Combining Text and Values in a Single String
Many tasks require a mixture of fixed words and variable values such as numbers or dates. MATLAB has functions that build such strings in a controlled way.
The compose function is particularly useful here. You specify a template string that contains placeholders, and compose fills those placeholders with values. For example,
name = "Alice";
score = 92.5;
msg = compose("Student %s scored %.1f points.", name, score);
creates a string "Student Alice scored 92.5 points.". The placeholder %s inserts text and %.1f inserts a number with one decimal place. The result msg is a string array that can have multiple rows if you pass vectors or matrices of values.
For a simpler situation where you only need to convert values to strings and then join them, you can use string together with concatenation. For instance,
x = 10;
s = "The value is " + string(x);
produces "The value is 10". The plus operator applies string concatenation. When you concatenate a string with a numeric value, MATLAB automatically converts the numeric part with string.
If you are working with character arrays and older code, you may see sprintf. It behaves similarly to compose, but returns characters instead of strings:
c = sprintf("Value: %.2f", 3.14159);
This returns a character row vector that reads "Value: 3.14".
Converting Between Strings and Character Arrays
MATLAB has both string arrays and character arrays. Sometimes you need to convert from one representation to the other, for example when you call a function that only accepts characters.
To convert from string to character array, you can use char. For example,
s = "hello";
c = char(s);
creates c as a character row vector 'hello'. If s has more than one element, char attempts to create a character array with one row for each string element, padding with spaces when needed.
The reverse conversion uses the string function. It converts character arrays to string arrays:
c = 'world';
s = string(c);
produces a scalar string "world". If c is a 2 dimensional character array with multiple rows, string(c) creates a string array with one string for each row.
These conversions are useful when you mix older and newer MATLAB code, or when you receive data in one form but want to use the features of the other form.
Converting Logical Values to and from Strings
Logical values represent true and false in MATLAB. Sometimes you want them to appear as the words "true" and "false" in a user message, a log file, or a table.
The conversion from logical to strings is simple with string. For example,
flag = [true false true];
s = string(flag);
creates a string array that contains "true", "false", and "true". If you convert back with logical, you need a numeric or logical source. For strings that contain the words "true" or "false", you cannot pass them directly to logical, so you must interpret them first. A typical pattern is to compare the string to "true" and use the result as a logical value:
s = "true";
isTrue = (s == "true");
Here isTrue is logical 1, which represents true.
Sometimes logical information is stored as "0" and "1" text. In that case, you can use str2double followed by logical:
s = ["0" "1" "1"];
x = logical(str2double(s));
This produces a logical array [0 1 1].
Converting Between Strings and Categorical Data
Categorical arrays store data that represents a fixed set of categories, such as "red", "green", and "blue". Conversion between strings and categorical values is common when you read text labels or when you want to display categories as text.
To create a categorical array from strings, use categorical. For instance,
colors = ["red" "green" "blue" "red"];
C = categorical(colors);
creates a categorical array C whose categories are "blue", "green", and "red". The elements of C refer to these categories internally, but you can still view them as text.
To convert a categorical array back to strings, use string:
labels = string(C);gives a string array with the same text labels as the original category names. This is useful when you want to export the labels to a file, concatenate them into messages, or process them with string functions.
Keep in mind that categories have a fixed set of allowed values. When converting from strings to categorical, MATLAB treats unique string values as categories. When you convert back, you get those exact labels again, even if some categories do not appear in the data.
Converting Datetime and Duration Values to Strings
Time related values such as datetime, duration, and calendarDuration often need to be converted to strings for display or export. The main function for this is string, and you can control the text format with the relevant properties or options of the time types themselves.
Suppose you have a vector of datetime values:
t = datetime(2024, 1, 1) + days(0:2);
s = string(t);
The variable s becomes a string array whose elements are formatted calendar dates. You can change the format of the datetime object before converting:
t.Format = "dd-MMM-yyyy";
s = string(t);
Now the strings match the new format, for example "01-Jan-2024".
The same pattern works for duration objects. If you have
d = hours(1:3);
s = string(d);
you get strings that show the numeric values with a time unit. Changing the Format property of the duration controls how the text looks, such as "hh:mm:ss" or "h".
For the reverse conversion, that is, from strings to datetime or duration, you use the time related constructors directly with strings:
s = "2024-01-01";
t = datetime(s, "InputFormat", "yyyy-MM-dd");
Here t is a datetime that matches the text. For duration you can write
s = "01:30:00";
d = duration(s, "InputFormat", "hh:mm:ss");
which creates a duration of one and a half hours.
Converting Strings to Other Types with Custom Rules
Sometimes you need to convert strings to more specific or complex types, such as custom codes, enums, or user defined structures. MATLAB does not provide a single general function for every possible custom type, but you can build your own rules using string comparison, indexing, and conditional logic.
A simple example is converting textual options into numeric codes. Suppose you have strings that say "low", "medium", or "high" and you want to map them to 1, 2, and 3. A direct approach is
levelStr = ["low" "medium" "high" "medium"];
levelNum = zeros(size(levelStr));
levelNum(levelStr == "low") = 1;
levelNum(levelStr == "medium") = 2;
levelNum(levelStr == "high") = 3;You can encapsulate such conversions in your own functions. Then you can reuse them throughout your code and ensure that all conversions follow the same rules.
For more structured types such as struct or table variables, you often combine string to number or string to categorical conversions with assignments into fields or columns. For instance, if a table column contains strings that represent categories, you can convert that column using categorical and keep the labels in sync.
Important points to remember:
Use string for modern conversions to and from strings, and num2str or sprintf only when you specifically need character arrays.
Prefer str2double over str2num for converting numeric text to numbers, because it is safer and does not evaluate arbitrary code.
Control how numbers appear in text with compose and appropriate format patterns, especially when you need fixed decimal places.
Convert between strings and categorical arrays with categorical and string to keep category labels consistent.
For time related values, rely on datetime, duration, and their Format and InputFormat properties together with string instead of manually building time strings.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!