MATLAB: Read values from headers in txt file as parameters, as well as separately reading data matrix from the rest of the file.

datadata importmatrixmatrix arraytext filevariables

Hello all,
If I have a txt file in the format of:
dt 0.001000
tfinal 50.000000
A 6000
B 22.0
C 36.000000
D 9000.000000
E 5.700000
F 15.000000
batch_run from t = 0 to 50 in steps of 0.001 with dt = 0.001
........................................................................
........................................................................
........................................................................
........................................................................
........................................................................
........................................................................
where ….. above represents a (n x m) data matrix.
How would it be best to go about reading the values from the headers (dt, tfinal, A,..,F) and setting them as new variables in my workspace, ignoring the line "batch_run from t = 0 to 50…".
Then in addition to this separately reading just the data matrix, creating a new variable in my workspace where all the headers have been removed and only the matrix remains.
Many thanks.

Best Answer

Obviously there's no built-in reader for that format of a file so you'll have to write your own. Use fgetl() like this:
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
% Read the remaining lines of the file.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
% Now parse the line
if contains(textLine, 'dt ')
elseif contains(textLine, 'tfinal ', 'IgnoreCase, true)
etc.
end
% All done reading all lines, so close the file.
fclose(fileID);
Basically you need to recognize when you are on a certain type of line and parse that line appropriately
Related Question