Reading datasets from .txt

조회 수: 3 (최근 30일)
Henry Ludwicki
Henry Ludwicki 2015년 11월 15일
편집: Mohammad Abouali 2015년 11월 15일
I have a dataset that has the following format in .txt.
Number of datasets
Number of lines in first data(ie: 500)
'0.0000e0,0'
'0.0000e0, 0.1'
(and goes on for 500 lines)
Number of lines in second dataset(ie 561)
and the pattern continues.
I'm trying to use textscan, but I'm new to matlab and finding it difficult to fit the format to textscan. Also theres 13000+ lines of data. Any help is appreciated.

채택된 답변

Mohammad Abouali
Mohammad Abouali 2015년 11월 15일
편집: Mohammad Abouali 2015년 11월 15일
Well something like this:
filename='tmp.txt';
fid=fopen(filename,'r');
if (fid==-1)
error('could not open %s for reading',filename);
end
nDataSet=fscanf(fid,'%d',1);
Data=cell(nDataSet,1);
for idx=1:nDataSet
nLines=fscanf(fid,'%d',1);
Data{idx}=fscanf(fid,'%f,%f',[2,nLines])';
end
fclose(fid);
You can access each data set using Data{dataSetNumber}. I generated some sample data set stored in a file called tmp.txt;(attached file). Here is the output.
>> Data{1}
ans =
1.0000 0
2.0000 0.9058
3.0000 0.1270
4.0000 0.9134
5.0000 0.6324
>> Data{2}
ans =
1.0000 0
2.0000 0.9058
3.0000 0.1270
4.0000 0.9134
5.0000 0.6324
1.0000 0
2.0000 0.9058
3.0000 0.1270
4.0000 0.9134
5.0000 0.6324
>> Data{3}
ans =
1.0000 0
2.0000 0.9058
3.0000 0.1270
If the input file really has ' at the begining and the end of the data then use the following code: (I have also attached tmp2.txt for you)
filename='tmp2.txt';
fid=fopen(filename,'r');
if (fid==-1)
error('could not open %s for reading',filename);
end
nDataSet=fscanf(fid,'%d',1);
Data=cell(nDataSet,1);
for idx=1:nDataSet
nLines=fscanf(fid,'%d',1);
tmpVar=strsplit(fscanf(fid,'%s',nLines),'''')';
Data{idx}=cell2mat(cellfun(@(c) str2num(c),tmpVar(2:end-1),'UniformOutput',false));
end
fclose(fid);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by