Convert vector of characters to doubles/numeric

Hi,
I have a column of characters I would like to convert to doubles
'1.0118'
'1.0075'
'1.0064'
'1.0077'
'1.0087'
'1.0213'
'1.0213'
'1.013'
'1.013'
'1.0047'
'1.0039'
'0.9993'
'1.0059'
'1.0047'
'0.9985'
I have tried using str2double but it doesn't seem to work. How would I go about converting this into a column of doubles?
Thank you

Answers (2)

Is it available as a cell array. If yes, then try this
x = {
'1.0118'
'1.0075'
'1.0064'
'1.0077'
'1.0087'
'1.0213'
'1.0213'
'1.013'
'1.013'
'1.0047'
'1.0039'
'0.9993'
'1.0059'
'1.0047'
'0.9985'};
y = cellfun(@str2num, x)

8 Comments

Thank you Ameer but this did not work becuase it is a char array. Do have any suggestions for this?
In MATLAB, character arrays cannot have a different number of characters in rows. For example
'1.0213'
'1.013'
'1.013'
'1.0047'
such a thing is not possible in a MATLAB array. Can you show in which form you have the characters? Maybe attach the variable in a .mat file.
So I am working with online data so I can't share the exact code becuase the API key to access the data is unique to the user. But I have attached a mat file below and also a screenshot of the original data location.
I am interested in extracting the column S.observations.value and transforming it from a character to double so that I can work with the data.
The screenshot is enough to give the idea. You can do something like this
numeric_values = str2double({S.Observations.value})
Thank you Ameer and Walter, this worked well. I guess I was missing something with the brackets!
I am also interested in extracting the dates from the 'date column and turning them into Matlab dates so that i could graph the values.
I have tried running
date = datetime((S.observations.date), 'InputFormat','yyyy-MM-dd')
but this seems not to work. I am following the Matlab 'datetime' format to turn characters into dates but it does not seem to work. Do you have any suggestions?
Thank you again for all your help.
You need to use braces instead of parenthesis
date = datetime({S.observations.date}, 'InputFormat','yyyy-MM-dd')
Thank you! This worked perfectly

Sign in to comment.

Categories

Products

Release

R2019b

Asked:

on 29 Oct 2020

Commented:

on 31 Oct 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!