Importing data from text file that is seperated by text
1 次查看(过去 30 天)
显示 更早的评论
I have this text file that is of the following nature:
DATA 1
X Y
1 2
2 3
DATA 2
X Y
1 2
2 3
I want to import the X and Y data of each Data group into MATLAB. My problem is that I want to do this with different text files, which all have the same general format, but will have differing number of data points. Is there a way to import the data without having to write specific code for each text file?
0 个评论
采纳的回答
Stephen23
2015-4-14
编辑:Stephen23
2015-4-20
fid = fopen('temp.txt','rt');
Grp1 = textscan(fid,'%f%f','HeaderLines',3);
Grp2 = textscan(fid,'%f%f','HeaderLines',3);
fclose(fid);
reads all the data of the attached file (see below), and produces these values:
>> cell2mat(Grp1)
ans =
1 2
3 4
>> cell2mat(Grp2)
ans =
5 6
7 8
This works because textscan reads all of the data that matches its format string until the first line that does not match. Then, because we do not close the file, we can simply call textscan again to continue reading from that line, so it continues to read the next group of data.
If the number of points/data-blocks varies or is large, then place this in a loop and put the values in a cell array, perhaps something like this:
out = {};
fid = fopen('temp.txt','rt');
tmp = textscan(fid,'%f%f','HeaderLines',3);
while ~isempty(tmp{1})
out(end+1,:) = tmp; %#ok<SAGROW>
tmp = textscan(fid,'%f%f','HeaderLines',3);
end
fclose(fid);
which gives all of the data in a cell array:
>> out
out =
[2x1 double] [2x1 double]
[2x1 double] [2x1 double]
>> out{3}
ans =
2
4
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!