Matlab

str2double in MATLAB

In MATLAB, the str2double() function plays a crucial role in converting character strings to numeric values. Whether you’re working with user inputs, reading data from files, or manipulating strings, str2double() provides a powerful tool to seamlessly convert strings into their numerical equivalents. This article will examine the MATLAB str2double() function’s syntax and offer several examples to highlight its usefulness.

The str2double() Function in MATLAB

The str2double() function in MATLAB converts a character string to a double-precision numeric value. Its syntax is as follows:

numericValue = str2double(string)

Here, string represents the character string that needs to be converted, and numericValue is the resulting double-precision numeric value.

Example 1: Converting a Simple Numeric String

string = '547.56';

numericValue = str2double(string);

disp(numericValue);

In this example, the str2double() function converts the character string 547.56 to its numeric equivalent, which is 547.56.

Example 2: Handling Invalid or Non-Numeric Strings

string = 'Hello MATLAB!';

numericValue = str2double(string);

if isnan(numericValue)

disp('Invalid or non-numeric string');

else

disp(numericValue);

end

In this example, the str2double() function is applied to the character string ‘Hello MATLAB!’, which is not a valid numeric string. The function returns NaN (Not-a-Number) because the conversion is not possible. The code then checks if the resulting value is NaN and displays an appropriate message to handle such cases.

A screenshot of a computer Description automatically generated with low confidence

Example 3: Converting Strings with Exponential Notation

string = '5.47e4';

numericValue = str2double(string);

disp(numericValue);

In this example, the str2double() function converts the character string 5.47e4 to its equivalent numeric value, which is 54700. The function handles strings with exponential notation, allowing for accurate conversion of scientific or engineering notation.

A screenshot of a computer Description automatically generated with low confidence

Conclusion

The str2double() function in MATLAB provides a reliable method to convert character strings to double-precision numeric values. By utilizing the syntax str2double(string), you can seamlessly convert strings into their numerical counterparts, enabling efficient data manipulation, analysis, and computation.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.