MATLAB Answers


How to read from a *.txt file to assign variables and paths

Asked by Samuel
on 24 Jul 2013

I would like to read from a text file that has the format of the following:






The purpose is to use this as an input file to import other files, HELLO.txt and GOODBYE.txt (in the same directory - /Users/asdf/xyz), and assign values for a few variables (XVALUE = 1 and YVALUE = 2).

Any help will be appreciated. Thanks!



No products are associated with this question.

1 Answer

Answer by Matt Kindig
on 24 Jul 2013
Edited by Matt Kindig
on 24 Jul 2013
 Accepted answer

Easiest way is to parse with regular expressions and read into an output structure with named fields.

 %read in file
  str = fileread('/path/to/your/file.txt');
  %extract fields and values
  pieces = regexp(str, '(?<field>\w+)=(?<value>[^\n]+)', 'names');
  out = struct();  %your variables
  for k=1:length(pieces),
     field = pieces(k).field;
     val = pieces(k).value;
     tf= ismember(val, char([34 39]));    %remove " and ' from string
     val = strtrim(val(~tf));    %also remove spaces
     %try to convert to double.  If successful, use converted value,
     %otherwise use original (string) value
     valn = str2double(val);
     if ~isnan(valn), %conversion successful, use as numeric
        val = valn;
     %add to output structure
     out.(field) = val;


on 24 Jul 2013

I am also dealing with somewhat similar situation.

I have around 50,000 files in a directory. File name format is like 20130724ABCD.txt (where letters stand for yyyy, mm, dd and text is for location).

ABCD is unique( e.g. COLO, NEBR, KANS), and I want to concatenate contents of file in a file ABCD.

How would I do it? Any help is greatly appreciated.

To clarify, you want to combine together the contents of all files which have the same 4-letter combo immediately prior to the file extension? If so, this is a bit different than the posted question, so you're better off starting a new question in this forum.

In particular, there are several Linux tools that would probably be faster and better for this task. Also, this can probably be done quite efficiently in Perl.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!