Read Textfile (lines with different formats) line by line
7 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a text file (lets call it an input file) of this type: My kind of input file % Comment 1 % Comment 2
4 %Parameter F
2.745 5.222 4.888 1.234 %Parameter X
273.15 373.15 1 %Temperature Initial/Final/Step
3.5 %Parameter Y
%Matrix A
1.1 1.3 1 1.05
2.0 1.5 3.1 2.1
1.3 1.2 1.5 1.6
1.3 2.2 1.7 1.4
I need to read this file and save the values as variables or even better as part of different arrays. For example by reading I should obtain Array1.F=4; then Array1.X should be a vector of 3 real numbers, Array2.Y=3.5 then Array2.A is a matrix FxF. There are tons of functions to read from text file but I don't know how to read these kind of different formats. I've used in the past fgetl/fgets to read lines but it reads as strings, I've used fscanf but it reads the whole text file as if it is formatted all equally. However I need something to read sequentially with predefined formats.. I can easily do this with fortran reading line by line because read has a format statement. What is the equivalent in MATLAB?
Best Regards and many thanks in advance Emanuel
0 个评论
回答(1 个)
Benjamin Kraus
2017-12-29
Within a for loop, you can read one line at a time using fgetl. Once you have the line, it looks like you need to determine where the % is in the line to know whether the data is before the % or if the data is on the next line. You could use find to find the index of the first %:
ind = find(str == '%',1);
if ind == 1
% Read next line for data
else
% Data is earlier in the line.
end
To determine the parameter name, I think regexp is the only option. For example:
out = regexp(str,'^(?<value>[^%]*)%(?<type>Parameter|Matrix) (?<name>[\S]+)','once','names')
The output from that statement should be a structure with three fields: value (the part before the %), type (the part immediately after the %), and name (the characters after either Parameter or Matrix). It won't work on the line that includes "Temperature Initial/Final/Step". You can either use a different pattern match for that (for example, you could just use contains or strfind to determine if the word 'Temperature' is in the line), or you can try to modify the expression I proposed. It isn't clear which would be easier.
Once you've separated those pieces, you can work with them all individually. You can use sscanf or str2num to convert the strings into doubles.
The last part you may need is how to use a variable to access a struct field. For example:
fieldname = out.name; % This is the 'F' or 'Y' or 'A' from above.
A.(fieldname) = str2num(out.value); % Store the value in the field of the struct.
That might be enough to get you started.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!