complicated formatted text with textscan
1 次查看(过去 30 天)
显示 更早的评论
Dear collegues, I am complicated reading a .txt with a peculiar format. This .txt file is an output of an R function, which I am running with vanilla inside matlab.... So i need to load this txt file programatically.
This is a part of the contents of the text file :
Reservoir_age_offset_14C_yrs_ranges at 90% confidence intervals
Identification_number: 1
MinRange MaxRange probability
-3962 -1741 90
Mode MidRange Median
-2709 -2852 -2761
Identification_number: 2
MinRange MaxRange probability
-9770 -8066 90
Mode MidRange Median
-8898 -8918 -8913
Identification_number: 3
MinRange MaxRange probability
-3762 4226 87.6
4335 4699 2.4
Mode MidRange Median
-559 468 305
Identification_number: 4
MinRange MaxRange probability
-401 2224 90
Mode MidRange Median
593 911 838
Identification_number: 5
MinRange MaxRange probability
-709 976 90
Mode MidRange Median
307 134 262
etc etc etc .................................................
So, to read this text format I implemented this script, the idea is to reconstruct a matrix from the numerical values in the text file
clear
here=pwd;
filename= 'output.txt';%ths is the text file
fileID2 = fopen(filename);
k=1;
Vale=[];
for j=1:50
s=cell2mat(textscan(fileID2,'%f',3,'headerlines',j,'collectoutput',1));
if isempty(s)==0 %rescue only valid solutions
Vale(:,k)=s; %brrrrrrppp!!
k=k+1;
end
end
fclose(fileID2);
The problem is that I cant read all the numerical values to reconstruct,
it works when I change the number of headerlines manually
e.g.
%s1=cell2mat(textscan(fileID2,'%f',3,'headerlines',7,'collectoutput',1))
However the loop provided incomplete nuber of values
Any idea or more elegant solution with this issue is highly appreciated
Thanks in advance
Jules
采纳的回答
Stephen23
2021-8-3
编辑:Stephen23
2021-8-3
This code imports the modified data file:
opt = {'CollectOutput',true, 'MultipleDelimsAsOne',true, ...
'HeaderLines',1, 'EndOfLine',':', 'Whitespace',' \b\t\n\r'};
fmt = '%f%*s%*s%*s%f%f%f%*s%*s%*s%f%f%f%*s';
fid = fopen('data.txt','rt');
tmp = textscan(fid,fmt,opt{:});
fclose(fid);
mat = tmp{1}
更多回答(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!