Obtaining data from a text file

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 个评论

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

请先登录,再进行评论。

 采纳的回答

Adam Danz
Adam Danz 2019-3-27
编辑:Adam Danz 2019-3-27
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 个评论

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!

请先登录,再进行评论。

更多回答(0 个)

产品

版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by