Separate string and perform math operations in Matlab
3 views (last 30 days)
Show older comments
Hello I have the following problem:
I have the string
num1 = '02 12 28.27'
I would like to perform operations with the numbers separately but first I need to separate the numbers, for example:
num_1 = 02
num_2 = 12
num_3 = 28.27
I was trying the following:
c = textscan(num1,'%f %f %f', 'Delimiter', ' ')
num1 = c{1}
num2 = c{2}
num3 = c{3}
I just got an empty vector.
Thanks in advance for your help!
1 Comment
Adam
on 14 Mar 2016
That is strange. If I run your code I get exactly what you are looking for. I wouldn't recommend going down the road of 3 named variables (I would use an array of num(1), num(2), num(3) instead), but that is a different matter entirely!
Accepted Answer
dpb
on 14 Mar 2016
Something's going in what what isn't shown; namely the actual code inline with the results instead of piecemeal describing what you think happened. As Adam notes, your input as given works fine although also as he says I'd do it somewhat differently...
>> num1 = '02 12 28.27';
>> cell2mat(textscan(num1,'%f','collectoutput',true))
ans =
2.0000
12.0000
28.2700
>>
Unless there's an embedded non-displaying character in your string other than \b, it appears your code should function albeit with the result of a cell array which is most easily overcome as noted by instead using 'collectoutput' to group into a single array and cell2mat to dispense with the cell array entirely from the git-go when it's not needed or wanted. Note there's no need to specify the delimiter specifically for the default set of whitespace but if it's a character other than blank by doing so you've caused a failure. But, what you pasted is a blank; what we can't tell is whether that's the case in the real instance.
Alternatively, for simple parsing such as this, str2num is less coding effort...
>> str2num(num1)
ans =
2.0000 12.0000 28.2700
>>
str2double, otoh, won't handle the multiple values in a string variable of a single line; it needs them to be a cellstring array or a single value if character string.
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!