Reading datasets from .txt

3 vues (au cours des 30 derniers jours)
Henry Ludwicki
Henry Ludwicki le 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.

Réponse acceptée

Mohammad Abouali
Mohammad Abouali le 15 Nov 2015
Modifié(e) : Mohammad Abouali le 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);

Plus de réponses (0)

Catégories

En savoir plus sur Text Data Preparation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by