spliting up a char array

2 views (last 30 days)
me
me on 7 Nov 2015
Edited: Stephen23 on 8 Nov 2015
If I have a char variable... say x=2.1*3C how can i get 2.1 by itself as its own variable
  2 Comments
me
me on 7 Nov 2015
I read a large text file full of GPS data and divided the string up by the using xc=textscan(scol{k,1}, '%s', 'Delimiter',','). Its in a for look and it scans sentences that look like this: $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*3C
Anyway, one of the points in this cell(scol{1,1}{18,1}) looks like this 2.1*3C but for my project I only need the numbers before the *. I have no idea how to get it or how I could have written my code differently.
me
me on 7 Nov 2015
i ment for loop not 'for look'

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 7 Nov 2015
Edited: Stephen23 on 8 Nov 2015
One answer to your question is to use indexing:
>> S = '2.1*3C'
S =
2.1*3C
>> T = S(1:3)
T =
2.1
If you want this as a numeric value then:
str2double(S(1:3))
Although there are many possible answers to your question, I suspect that this whole thing could be avoided by better planning and data concept. Could you please give us more information about what you are trying to do with the 2.1, and where this string comes from. Probably passing the data in something more suitable than a string would make your programming much simpler and more reliable.
  2 Comments
me
me on 7 Nov 2015
Thank you! that worked perfectly.
Image Analyst
Image Analyst on 7 Nov 2015
If it was "perfect" then you can also "vote" for the answer to give him double reputation points. That'd be a nice thing to do for him.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 7 Nov 2015
Some of the millions of ways:
% Set up (if the x= is part of the string):
myString = 'x=2.1*3C'
% Find the equal sign:
equalIndex = strfind(myString, '=');
% Find the *:
starIndex = strfind(myString, '*');
% Now get 2.1 in its own character variable:
itsOwnVariable = myString(equalIndex+1:starIndex-1) % as another string
% Now get 2.1 in its own character variable:
itsOwnVariable = str2double(myString(equalIndex+1:starIndex-1)) % As a double
% Set up with no x= in the string:
myString = '2.1*3C'
% Now get 2.1 in its own character variable:
itsOwnVariable = myString(1:3) % as another string
% Now get 2.1 in its own character variable:
itsOwnVariable = sscanf(myString, '%f') % As a double

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!