str2num

Evaluates text as a MATLAB expression and returns its numeric value.

Category: Language Fundamentals > Data Types

Syntax

X = str2num(str)

Evaluates str and returns the result.

[X, tf] = str2num(str)

Also returns whether the conversion succeeded.

Description

str2num wraps the text in brackets and runs it through eval, so it understands matrices, arithmetic and function calls, not just literal numbers. For that reason it can run arbitrary code, and it is slow for large amounts of text.

When the text is only a number, prefer str2double, which is faster, safe, and returns NaN instead of an empty matrix on failure.

Input arguments

str
Character vector or string holding a numeric expression, such as '[1 2; 3 4]' or '2*pi'.

Output arguments

X
The value of the expression, or [] if it could not be evaluated.
tf
true if the conversion worked, false otherwise.

Example

Matrix, expression and failure

A = str2num('[1 2; 3 4]')
[v, ok] = str2num('2*pi')
[w, ok2] = str2num('hello world(')
Output
A = 2×2

     1     2
     3     4
v = 6.2832
ok = logical
   1
w = []
ok2 = logical
   0

See also

str2double eval num2str sscanf