フィルターのクリア

How to read a selected number from a string?

4 ビュー (過去 30 日間)
Novice Geek
Novice Geek 2014 年 2 月 13 日
コメント済み: the cyclist 2014 年 2 月 13 日
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

採用された回答

Jos (10584)
Jos (10584) 2014 年 2 月 13 日
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 件のコメント
Novice Geek
Novice Geek 2014 年 2 月 13 日
That works like a charm. Thank you!

サインインしてコメントする。

その他の回答 (1 件)

the cyclist
the cyclist 2014 年 2 月 13 日
編集済み: the cyclist 2014 年 2 月 13 日
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 件のコメント
Novice Geek
Novice Geek 2014 年 2 月 13 日
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 2014 年 2 月 13 日
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().

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by