Value associate to a parameter in a text

So I have a text file similar to the following:
DELZZ 3301.23
KUTY 4.32 SERI -0.023
I want Matlab to read the file and return values associate to each parameter (DELZZ, KUTY,SERI,...) Any suggestion?

 채택된 답변

Paolo
Paolo 2018년 7월 9일
편집: Paolo 2018년 7월 9일

0 개 추천

data = fileread('mytextfile.txt');
val = regexp(data,'(?<=\s)(-?\d*\.?\d*)(?=\s|$)','match');

댓글 수: 7

Jack
Jack 2018년 7월 9일
what does -?\d+\.?\d+ do?
Paolo
Paolo 2018년 7월 9일
편집: Paolo 2018년 7월 9일
It's a regular expression which you can see in action live here.
  • -? Matches a negative sign optionally.
  • \d+ Matches digits.
  • \. Matches a decimal point optionally.
  • \d+ Matches more digits.
The output is:
val:
{'3301.23'} {'4.32'} {'-0.023'}
If you need to perform numerical calculations you need to convert the character vectors to doubles:
val = cellfun(@str2double,val);
Does that help you?
Jack
Jack 2018년 7월 9일
편집: Jack 2018년 7월 9일
Thank you so much. And the last question, what if the name of parameters contained number, like
KUTY01 33.02
Fuzzy10 -0.923
or is it possible to ask Matlab: go ahead and find a value in front of a particular parameter? like find the value in front of "KUTY01" and it returns 33.02
If you wanted the result for a specific case, i.e. KUTY01, you can use:
(?<=KUTY01\s)-?\d+\.?\d+
The first part of the regular expression (?<=KUTY01\s) is a positive lookbehind.
As you can see here, it checks backwards to see if pattern KUTY01, followed by whitespace, is found. If it is, it matches the sequence of digits, decimal point and digits as explained in the previous comment. As you can see, only 33.02 is now matched.
If you found the answer useful consider accepting it/voting :)
Jack
Jack 2018년 7월 9일
it seems this command doesn't read a single digit number like
KUTY01 5
is that right?
That's right, you will need to use the greedy * quantifier rather than the + quantifier. Since you need to match those values too, use:
(?<=KUTY01\s)-?\d*\.?\d*
I'll update my answer.
Jack
Jack 2018년 7월 9일
Thank u so much

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2018년 7월 9일

댓글:

2018년 7월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by