Matlab

How to Convert String to a Number in MATLAB?

Strings manipulation is one of the fundamental activities of MATLAB programming, and those who are proficient in it can often find ways to automate tasks and improve their code. For example, converting strings to numbers can be helpful for performing mathematical operations or storing them in numerical data structures.

Read this guide to convert string to a number in MATLAB.

How to Convert String to a Number in MATLAB

In MATLAB, you can convert a string to a number:

1: How to Convert String to a Number in MATLAB Using the str2num() Function?

The str2num() is a built-in MATLAB function designed especially for string manipulation tasks. The name of this function suggests that you can use it in your MATLAB code to easily convert string to a number. The str2num() function is straightforward where you only have to pass the string and it will quickly convert it into a number.

Syntax
The str2num() function uses the following syntax in MATLAB.

str2num(string)

Where in place of string, you can pass any string you want.

Example
The following example will convert the string into a number using the str2num() function in MATLAB.

X = str2num('12 3.9 -9.82 3.47; 5 6.2 8.9 33')

2: How to Convert String to a Number in MATLAB Using the str2double() Function?

There is another built-in function in MATLAB called str2double() that can also be used for converting a string to a number. This function works similarly to str2num() but is more robust and handles complex input strings.

Syntax
The str2double() has the following syntax in MATLAB:

str2double(string)

Here string is a text that represents real or complex numeric values.

Example
The following example will convert the string into a number using the str2double() function in MATLAB.

X = str2double('3.448e8')

You can follow here for more details about str2double() function in MATLAB.

Conclusion

Converting strings to numbers is a useful task in MATLAB programming. There are two widely used functions: str2num() and str2double() that can be used to easily convert any string into a number in MATLAB. By following these methods with their examples, you will quickly learn these functions’ usage, which you can later on use in your MATLAB codes.

About the author

Awais Khan

I'm an Engineer and an academic researcher by profession. My interest for Raspberry Pi, embedded systems and blogging has brought me here to share my knowledge with others.