在数学建模中遇到的数据比较难处理,而且给的是text格式,自己想了好长时间才编出来,现在分享一下,可以交流学习
目标的text文件是
只提取里面的数据
需要自编函数
clc,clear
path='D:\matlab文件\zz\';
namelist=dir([path,'*.txt']);
nam=length(namelist);
file=dir('zz\*.txt');
sign=1;
for n=1:nam
filename{n}=[path,namelist(n).name];
% [data1,data2]=textread(filename,'%s%s','delimiter', ':','headerlines',6);
% [a1,a2]=size(data2);
% for i=1:a1
% s(i,:)=char(data2(i,:));
% end
% datas(2)
% for i=1:a1
% s(i)=regexp(datas(i,:),' ','split')
% end
% for i=1:a1
% s=char(data2(i));
% datas(i)='s';
% end
% fid=fopen('data.txt','w');
% fprintf(fid,'%c',data2);
% fclose(fid);
s=[]
fg=4
fid=fopen(filename{n},'r');
while ~feof(fid)
str = fgetl(fid)
em=isempty(str)
if em==0
if str(1)=='1'&&str(2)=='1'
continue
end
if str(1)=='时'
st1=str(1,4:7);
st2=str(1,9:10);
st3=str(1,12:13);
s(1)=str2num(st1);
s(2)=str2num(st2);
s(3)=str2num(st3);
end
if str(1)=='0'||str(1)=='1'||str(1)=='2'||str(1)=='3'||str(1)=='4'
[a1,a2]=size(str);
for i=1:a2
if str(i)==':'
left=i+1;
break
end
end
right=a2;
for i=left:a2
if str(i)==' '
right=i
break
end
end
s(fg)=str2num(str(1,left:right));
fg=fg+1;
end
end
end
sx(sign,:)=s;
sign=sign+1;
end
clc,clear
data=xlsread('zz0.xlsx');
[a1,a2]=size(data);
data0=[]
flag=1;
for i=1:a1
if data(i,8)>100&&data(i,11)>10
data0(flag,:)=data(i,:);
flag=flag+1;
end
end
xlswrite('zq.xlsx',data0)
clc,clear
data=xlsread('zq.xlsx');
[a1,a2]=size(data);
datas=[]
flag=1;
datas(1,:)=data(1,:);
% if i<=264
% pp=0;
% while data(i,2)==datas(i-1,:2)&&data(i,3)==data(i-1,:3)
% pp=pp+1;
% i=i+1;
% end
% if
for i=2:a1
if data(i,2)==datas(flag,2)&&data(i,3)==datas(flag,3)
blan=data(i,:)+datas(flag,:);
blan=blan./2;
datas(flag,:)=blan;
else
flag=flag+1;
datas(flag,:)=data(i,:);
end
end
xlswrite('zq1.xlsx',datas)
标签:end,fid,text,a1,a2,matlab,str,data,逐行
来源: https://www.cnblogs.com/zq-dmhy/p/11325264.html