필터 지우기
필터 지우기

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개)

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 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