2

我想将 .txt 文件读入 Matlab。其中一列包含字母和数字。(所以我想一种方法是将此列作为字符串读取。)

问题是我还需要找出该列中大于 5 的数字。

例如 .txt 看起来像

12 1
21 2
32 7
11 a
03 b
22 4
13 5
31 6

即最终,我想得到

32 7
31 6

我怎么才能得到它??请哪位高手帮忙!

4

2 回答 2

4

您可以使用 TEXTSCAN 将文件的内容读入字符串元胞数组,使用CELLFUNSTR2NUM字符串转换为数值(字符如'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
于 2011-06-03T21:27:48.983 回答
0
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);

违反了在循环期间增加 Matlab 变量的潜规则,但无论如何它都是文本处理,因此您可能不会注意到速度缓慢。

编辑:以前的版本有太多错误,必须重新开始。

于 2011-06-03T21:21:12.537 回答