Reading datasets from .txt
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Henry Ludwicki
am 15 Nov. 2015
Bearbeitet: Mohammad Abouali
am 15 Nov. 2015
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.
0 Kommentare
Akzeptierte Antwort
Mohammad Abouali
am 15 Nov. 2015
Bearbeitet: Mohammad Abouali
am 15 Nov. 2015
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Text Data Preparation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!