您可以使用TEXTSCAN 将文件的内容读入字符串元胞数组,使用CELLFUN 和STR2NUM 将字符串转换为数值('a' 和'b' 等字符将导致空矩阵 []),删除单元格数组中包含任何空单元格的行,然后使用 CELL2MAT 将剩余数据转换为 N×2 矩阵:
fid = fopen('junk.txt','r'); %# Open the file
data = textscan(fid,'%s %s','CollectOutput',true); %# Read the data as strings
fclose(fid); %# Close the file
data = cellfun(@str2num,data{1},'UniformOutput',false); %# Convert to numbers
data(any(cellfun('isempty',data),2),:) = []; %# Remove empty cells
data = cell2mat(data); %# Convert to N-by-2 array
考虑到问题中的示例文件,矩阵data 现在看起来像这样:
>> data
data =
12 1
21 2
32 7
22 4
13 5
31 6
您可以像这样在第二列中获取值大于 5 的行:
>> data(data(:,2) > 5,:)
ans =
32 7
31 6