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 Kommentar

Christian F
Christian F am 27 Mär. 2019
The quotations are not actually part of the text document, btw.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Adam Danz
Adam Danz am 27 Mär. 2019
Bearbeitet: Adam Danz am 27 Mär. 2019

1 Stimme

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 Kommentare

Christian F
Christian F am 27 Mär. 2019
Bearbeitet: Christian F am 27 Mär. 2019
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?
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 am 27 Mär. 2019
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 am 27 Mär. 2019
Oh. Oops. Yeah, the code works now! Thanks for your help and your patience!
Adam Danz
Adam Danz am 27 Mär. 2019
Great!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Version

R2018b

Gefragt:

am 27 Mär. 2019

Kommentiert:

am 27 Mär. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by