Kahibaro
Discord Login Register

Converting Between Data Types and Strings

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

matlab
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

matlab
s = compose(formatPattern, values);

Here formatPattern is a string that describes how each value should appear. For example,

matlab
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,

matlab
c = num2str(123.456);

produces a row vector of characters such as '123.456'. num2str lets you specify a precision too:

matlab
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,

matlab
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,

matlab
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,

matlab
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,

matlab
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,

matlab
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:

matlab
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,

matlab
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:

matlab
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,

matlab
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:

matlab
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:

matlab
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,

matlab
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:

matlab
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:

matlab
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:

matlab
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

matlab
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:

matlab
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

matlab
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

matlab
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: 3

Comments

Please login to add a comment.

Don't have an account? Register now!