String 将复杂的.txt文件读入Matlab
我想把一个.txt文件读入Matlab。 其中一列包含字母和数字。 (因此,我想一种方法是将此列作为字符串阅读。) 问题是我还需要找出该列中大于5的数字 e、 txt看起来像String 将复杂的.txt文件读入Matlab,string,matlab,file-io,textscan,String,Matlab,File Io,Textscan,我想把一个.txt文件读入Matlab。 其中一列包含字母和数字。 (因此,我想一种方法是将此列作为字符串阅读。) 问题是我还需要找出该列中大于5的数字 e、 txt看起来像 12 1 21 2 32 7 11 a 03 b 22 4 13 5 31 6 i、 最终,我希望 32 7 31 6 我怎样才能得到它??任何专家,请帮助 fid=fopen('txt.txt','r'); fid = fopen('txt.txt','r'); Aout = []; while(1)
12 1
21 2
32 7
11 a
03 b
22 4
13 5
31 6
i、 最终,我希望
32 7
31 6
我怎样才能得到它??任何专家,请帮助 fid=fopen('txt.txt','r');
fid = fopen('txt.txt','r');
Aout = [];
while(1)
[a1,count1] = fscanf(fid,'%s',1);
[a2,count2] = fscanf(fid,'%s',1);
if(count1 < 1 | count2 < 1)
break;
end
if(~isempty(str2num(a2)) & str2num(a2) > 5 & (~isempty(str2num(a1))) )
Aout = [ Aout ; str2num(a1) str2num(a2) ];
end
end
fclose(fid);
Aout=[];
而(1)
[a1,count1]=fscanf(fid,'%s',1);
[a2,count2]=fscanf(fid,'%s',1);
如果(计数1<1 |计数2<1)
打破
结束
如果(~isempty(str2num(a2))&str2num(a2)>5&(~isempty(str2num(a1)))
Aout=[Aout;str2num(a1)str2num(a2)];
结束
结束
fclose(fid);
违反了在循环过程中增加Matlab变量的潜规则,但这是文本处理,因此您可能不会注意到缓慢
编辑:在以前的版本中有太多错误,必须重新开始。您可以使用将文件内容读入字符串的单元格数组,使用and将字符串转换为数值(像
'a'
和'b'
这样的字符将导致空矩阵[]
),删除单元格数组中包含任何空单元格的行,然后使用以下命令将剩余数据转换为N×2矩阵:
考虑到问题中的示例文件,矩阵数据
现在将如下所示:
>> data
data =
12 1
21 2
32 7
22 4
13 5
31 6
您可以在第二列中获得值大于5的行,如下所示:
>> data(data(:,2) > 5,:)
ans =
32 7
31 6
>> data(data(:,2) > 5,:)
ans =
32 7
31 6