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.
Related videos on Youtube
Author by
abhishek
Updated on June 04, 2022Comments
-
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 over 10 yearshas been answered many times, but see my answer on how to apply
str2num
(or betterstr2double
) on each element of a cell array.
-
-
yuk over 10 yearsYou don't need cellfun. str2double perfectly works with cell arrays.
-
gevang over 10 years@yuk good point. updated. As a side-note, this applies only to
str2double()
though, and notstr2num()
. -
Max almost 7 yearsstr2double is around 10-20% slower than cellfun with string2mat.