I'm relatively new to MatLab, and I'm having trouble extracting a specific number from a text file. The text file reads as follows:
"Whatever=43
this is not it =3
start=2300"
What function do I use to return 2300 (and as a number format of some sort, like a double or a single, rather than a string)?

1 件のコメント

Christian F
Christian F 2019 年 3 月 27 日
The quotations are not actually part of the text document, btw.

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

 採用された回答

Adam Danz
Adam Danz 2019 年 3 月 27 日
編集済み: Adam Danz 2019 年 3 月 27 日

1 投票

I've attached the sample text file to run this demo. In the 3rd line of code, a regular expression is used to search for the row of text that contains the key word "start". If you have more than 1 row of text that contains that word, you'll need to adapt this.
% read file --> char array
content = fileread('textfile.txt');
% Break up each line of char array into cell of strings
contentStr = strsplit(content, '\n');
% Locate string that contains the key ("start")
target = contentStr{~cellfun(@isempty,regexp(contentStr, 'start'))};
% Isolate the numeric value
val = str2double(target(regexp(target, '=')+1 : end));
% val =
% 2300

5 件のコメント

Christian F
Christian F 2019 年 3 月 27 日
編集済み: Christian F 2019 年 3 月 27 日
I'm getting the error message:
"Undefined function or variable 'content'.
Error in noname (line 12)
contentStr = strsplit(content, '\n');"
Am I supposed to put in something for content?
Adam Danz
Adam Danz 2019 年 3 月 27 日
I updated my code above. The original final line was
val = str2double(regexp(target, '\d+', 'match'));
but this wouldn't work if there were decimal values such as start = 2300.5;
Adam Danz
Adam Danz 2019 年 3 月 27 日
In the first line of my code I create the variable 'content'. That variable is an input in the 2nd line. It looks like you're running the 2nd line without running the first line.
Christian F
Christian F 2019 年 3 月 27 日
Oh. Oops. Yeah, the code works now! Thanks for your help and your patience!
Adam Danz
Adam Danz 2019 年 3 月 27 日
Great!

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

その他の回答 (0 件)

製品

リリース

R2018b

質問済み:

2019 年 3 月 27 日

コメント済み:

2019 年 3 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by