Octave's str2num function

In the Octave script for computing the binomial distribution that I posted a few days ago, I used the str2num function to covert command-line arguments, which the argv function returns as strings, into numbers. It turns out that str2num can do more than that.

Here’s a brief Octave session demonstrating str2num’s power:

octave-3.2.3:1> str2num('5')
ans =  5
octave-3.2.3:2> str2num('5.33')
ans =  5.3300
octave-3.2.3:3> str2num('5+7')
ans =  12
octave-3.2.3:4> str2num('(5+7)/5')
ans =  2.4000
octave-3.2.3:5> str2num('sin(pi/4)')
ans =  0.70711
octave-3.2.3:6> str2num('fred')
ans = [](0x0)
octave-3.2.3:7> str2num('[1, 2].^2')
ans =

   1   4

Rather than just converting a string to a number, str2num evaluates the string as an Octave expression and then returns the result as a number. More generally, if the result is an array of numbers, it will return that array. Only if the result cannot be interpreted as a number will str2num fail, and even in that case it won’t issue an error message; Perl-like, it will just return an empty array.

This makes my binomial script even easier to use. Recall that to demonstrate it, I ran

binomial 10 .166667  

to get the distribution of ones for 10 rolls of a standard six-sided die. I could have used the simpler

binomial 10 1/6

and taken advantage of the power of str2num to get the same result

 0  0.161506
 1  0.323011
 2  0.290710
 3  0.155045
 4  0.054266
 5  0.013024
 6  0.002171
 7  0.000248
 8  0.000019
 9  0.000001
10  0.000000

Strangely, the Octave documentation for str2num doesn’t mention that it does an expression evaluation, but the documentation for a similar function, str2double says:

str2double can replace str2num, but avoids the use of eval on unknown data.

which is a pretty good hint that str2num does an evaluation, but it would be nice if the docs did more than hint.

Tags: