How to convert the string 'pi' to double? (MATLAB 2015a)

Viewed 186

When I try to convert the string 'pi' to a double it gets converted to NaN.

>> str2double('pi')

ans =

   NaN

I'm reading a file that contains comma separated values, which might include a multiple of pi. For example (assume pi_in_string was read from a file):

>> pi_in_string = '0,1,-pi/6'

pi_in_string =

0,1,-pi/6

>> split_string = strsplit(pi_in_string, ',')

split_string = 

    '0'    '1'    '-pi/6'

>> str2double(split_string)

ans =

     0     1   NaN
2 Answers

I figured out that I need to use str2num instead of str2double, but str2num doesn't work on a cell array. So instead, I looped through the elements in the cell array, converting each to type char first, then using str2num.

pi_in_string = '0,1,-pi/6';
str_array    = strsplit(pi_in_string, ',');  %str_array now cell array
num_elements = length(str_array);            %get # elements to loop
num_vector   = zeros(1,num_elements);        %initialize vector

                                             %loop through elements in str_array
for i = 1:num_elements                       %converting each element first to type char

    num_vector(i) = str2num(char(str_array(i)));

end

It is easy to avoid the for loop and explicitly initializing the num_vector array using the cellfun command:

pi_in_string = '0,1,-pi/6';
str_array = strsplit(pi_in_string, ',');
num_vector = cellfun(@(x)eval(x), str_array, 'UniformOutput', true)

num_vector =
     0    1.0000   -0.5236
Related