Convert an array of strings to a vector of numbers

11,851

Given that you have a cell array of string values, you can use cellfun to apply str2num conversion on each entry. The output will be a vector/matrix of the converted values.

d = {'2.3','3.5'}
dVec = cellfun(@str2num, d);

However, you are better using str2double than str2num. From the documentation:

Note: str2num uses the eval function to convert the input argument. Side effects can occur if the string contains calls to functions. Using str2double can avoid some of these side effects.

dVec = cellfun(@str2double, d);

Update: As @yuk points out, you can call str2double() directly on the cell array for the same output.

dVec = str2double(d);

Note that the same call with str2num() will give the "must be a string or string array" error.

Share:
11,851

Related videos on Youtube

abhishek
Author by

abhishek

Updated on June 04, 2022

Comments

  • abhishek
    abhishek over 1 year

    I have this:

    d = {'2.5', '3.5'};
    d = 
    '2.5'    '3.5'
    

    How do I convert it to a vector of numbers?

    d = 2.5   3.5
    
    • gevang
      gevang over 10 years
      has been answered many times, but see my answer on how to apply str2num (or better str2double) on each element of a cell array.
  • yuk
    yuk over 10 years
    You don't need cellfun. str2double perfectly works with cell arrays.
  • gevang
    gevang over 10 years
    @yuk good point. updated. As a side-note, this applies only to str2double() though, and not str2num().
  • Max
    Max almost 7 years
    str2double is around 10-20% slower than cellfun with string2mat.