MATLAB Answers

From char to number

1 028 views (last 30 days)
paul kaam
paul kaam on 12 May 2015
Edited: Walter Roberson on 6 Nov 2020
Hi ,
I have this:
"10:58",297.98,0.25,0.15,66.5,1.194,-0.31,-0.27,71.1,0.966,""
it is of type char.
it contains the following numbers and one time value:
10:58 (time)
297.98
0.25
0.15
66.5
1.194
-0.31
-0.27
71.1
0.966
how can i convert this char type to individual numbers? I could not find it on internet i tried multiple things with char2[anything]
many thanks,
Paul

Answers (3)

Robbin van Hoek
Robbin van Hoek on 12 May 2015
try str2num!
>> str2num('6.1')
ans =
6.1000
  1 Comment
paul kaam
paul kaam on 12 May 2015
but it is of type char, if i do str2num i get the result : ans = [ ]

Sign in to comment.


Walter Roberson
Walter Roberson on 12 May 2015
S = '"10:58",297.98,0.25,0.15,66.5,1.194,-0.31,-0.27,71.1,0.966,""';
C = textscan(S, '"%[^"]",%f,%f,%f,%f,%f,%f,%f,%f,%f,%*s', 'CollectOutput', 1);
thetimestr = C{1}{1};
thenums = C{2};
  9 Comments
paul kaam
paul kaam on 12 May 2015
Now it is between '' with cellstr:
>> S
S =
"12:15",333.98,0.06,0.06,65.3,0.975,0.02,0.10,72.2,1.002,""
>> cellstr(S)
ans =
'"12:15",333.98,0.06,0.06,65.3,0.975,0.02,0.10,72.2,1.002,""'
>> C = textscan(ans, '"%[^"]",%f,%f,%f,%f,%f,%f,%f,%f,%f,%*s', 'CollectOutput', 1); Error using textscan First input must be of type double or string.

Sign in to comment.


omax ali
omax ali on 5 Nov 2020
i just write this for new ones who searching:
to change some value like a=["1","2.2","3",......] to number format we can do as:
b=char(a);
c=str2num(b);
c gives you the numbers.
  1 Comment
Walter Roberson
Walter Roberson on 6 Nov 2020
a=["1","2.2","3"]
a = 1×3 string array
"1" "2.2" "3"
double(a)
ans = 1×3
1.0000 2.2000 3.0000
This relies upon a being datatype string and not cell array of character vector:
a = {'1', '2.2', '3'}
a = 1x3 cell array
{'1'} {'2.2'} {'3'}
str2double(a)
ans = 1×3
1.0000 2.2000 3.0000

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!