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 commentaire

Christian F
Christian F le 27 Mar 2019
The quotations are not actually part of the text document, btw.

Connectez-vous pour commenter.

 Réponse acceptée

Adam Danz
Adam Danz le 27 Mar 2019
Modifié(e) : Adam Danz le 27 Mar 2019
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 commentaires

Christian F
Christian F le 27 Mar 2019
Modifié(e) : Christian F le 27 Mar 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 le 27 Mar 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 le 27 Mar 2019
Oh. Oops. Yeah, the code works now! Thanks for your help and your patience!
Adam Danz
Adam Danz le 27 Mar 2019
Great!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by