Separate string and perform math operations in Matlab

조회 수: 4 (최근 30일)
Francisco
Francisco 2016년 3월 14일
댓글: Francisco 2016년 3월 15일
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
Adam
Adam 2016년 3월 14일
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!

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2016년 3월 14일
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.
  댓글 수: 1
Francisco
Francisco 2016년 3월 15일
Thanks a lot for the explanations! it works perfectly.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by