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 Comment

The quotations are not actually part of the text document, btw.

Sign in to comment.

 Accepted Answer

Adam Danz
Adam Danz on 27 Mar 2019
Edited: Adam Danz on 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 Comments

Christian F
Christian F on 27 Mar 2019
Edited: Christian F on 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;
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.
Oh. Oops. Yeah, the code works now! Thanks for your help and your patience!

Sign in to comment.

More Answers (0)

Products

Release

R2018b

Asked:

on 27 Mar 2019

Commented:

on 27 Mar 2019

Community Treasure Hunt

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

Start Hunting!