【问题标题】:Making a matrix of strings read in from file using feof function in matlab使用matlab中的feof函数从文件中读取字符串矩阵
【发布时间】:2013-07-22 22:44:30
【问题描述】:

我有一个如下所示的索引文件(称为 runnumber_odour.txt):

run00001.txt   ptol
run00002.txt   cdeg
run00003.txt   adef
run00004.txt   adfg

我需要某种方式将其加载到 matlab 中的矩阵中,以便我可以搜索第二列以找到其中一个字符串,加载相应的文件并对其进行一些数据分析。 (即如果我搜索“ptol”,它应该加载 run00001.txt 并分析该文件中的数据)。

我试过这个:

clear; clc ;
% load index file - runnumber_odour.txt
runnumber_odour = fopen('Runnumber_odour.txt','r');
count = 1;
lines2skip = 0;

while ~feof(runnumber_odour)

 runnumber_odourmat = zeros(817,2);
 if count <= lines2skip
     count = count+1;
     [~] = fgets(runnumber_odour); % throw away unwanted line
     continue;
 else
     line = strcat(fgets(runnumber_odour));
     runnumber_odourmat = [runnumber_odourmat ;cell2mat(textscan(line, '%f')).'];
     count = count +1;
   end
end

runnumber_odourmat

但这只会产生一个 817 x 2 的零矩阵(即不写入矩阵),但没有行 runnumber_odourmat = zeros(817,2);我收到错误“未定义的函数或变量'runnumber_odourmat'。

我也试过用 strtrim 代替 strcat 但这也不起作用,同样的问题。

那么,如何将该文件加载到 matlab 中的矩阵中?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以使用 Map 对象轻松完成所有这些操作,因此您无需进行任何搜索或类似的操作。您的第二列将成为第一列的关键。代码如下

    clc; close all; clear all;
    fid = fopen('fileList.txt','r'); %# open file for reading
    count = 1;
    content = {};
    lines2skip = 0;
    fileMap = containers.Map();
    while ~feof(fid)
        if count <= lines2skip
            count = count+1;
            [~] = fgets(fid); % throw away unwanted line
        else
            line = strtrim(fgets(fid));
            parts = regexp(line,' ','split');
            if numel(parts) >= 2
                fileMap(parts{2}) = parts{1};
            end
            count = count +1;
        end
    end
    fclose(fid);
    
    fileName = fileMap('ptol')
    
    % do what you need to do with this filename
    

    这将提供对任何元素的快速访问

    然后,您可以按照我提供的答案执行上一个问题中描述的操作。

    【讨论】:

    • 感谢您,它似乎与给出此错误的最后一行不同:Error using containers.Map/subsref The specified key is not present in this container。 filemaptest 中的错误(第 28 行)fileName = fileMap('ptol')
    猜你喜欢
    • 1970-01-01
    • 2012-03-04
    • 2015-10-06
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多