Effacer les filtres
Effacer les filtres

How to read a selected number from a string?

4 vues (au cours des 30 derniers jours)
Novice Geek
Novice Geek le 13 Fév 2014
Commenté : the cyclist le 13 Fév 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

Réponse acceptée

Jos (10584)
Jos (10584) le 13 Fév 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
  1 commentaire
Novice Geek
Novice Geek le 13 Fév 2014
That works like a charm. Thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

the cyclist
the cyclist le 13 Fév 2014
Modifié(e) : the cyclist le 13 Fév 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 commentaires
Novice Geek
Novice Geek le 13 Fév 2014
Thank you for your reply. This seems to work. But now I get the following error:
Undefined function 'str' for input arguments of type 'double'.
I tried removing str and replaced with double and removed str2num function, there there is no error but I get the following result
num = 20 21 22 23 24
the cyclist
the cyclist le 13 Fév 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().

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by