How to read a selected number from a string?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Novice Geek
am 13 Feb. 2014
Kommentiert: the cyclist
am 13 Feb. 2014
Hello,
I have a string:
# Source Interval: 22.99 u (ID: 2)
and I want to read only 22.99 from this string. This number can change in different files as I have multiple files with same string but a different number ranging upto ten thousand. I tried retrieving this number using strread, but everytime I get the error Number of outputs must match the number of unskipped input fields.
Can anyone help?
Thank you
0 Kommentare
Akzeptierte Antwort
Jos (10584)
am 13 Feb. 2014
str = '# Source Interval: 22.99 u (ID: 2)'
v = strread(str,'# Source Interval: %f%*[^\n]')
% The format specifier means the following
% - '%f' - read a floating point number
% - '%*[^\n]' - ignore the rest of the string
Weitere Antworten (1)
the cyclist
am 13 Feb. 2014
Bearbeitet: the cyclist
am 13 Feb. 2014
There are multiple ways to do this. Which one is best may depend on how consistent the rest of the text is.
The regexp() command should be able to do everything you need. For example, take a look at this code:
str = '# Source Interval: 22.99 u (ID: 2)';
colonIdx = regexp(str,':');
uIdx = regexp(str,'u');
numRange = colonIdx(1)+2 : uIdx(2)-2;
num = str2num(str(numRange))
Here, I relied on the fact that your numeric string came the first occurrence of a colon and the second occurrence of the letter "u". I used regexp() to find the locations of those characters, and then the relative location of the number.
2 Kommentare
the cyclist
am 13 Feb. 2014
I can't be 100% sure what went wrong, without seeing your code, but here is a guess:
"str" is the variable name I gave to your string '# Source Interval: 22.99 u (ID: 2)'. If you decided to name that string something else, then you need to make that replacement everywhere in the code I posted. Otherwise, MATLAB thinks you are trying to call a function named str().
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!