0

我一直在尝试从格式化的文本文件中读取一些数字。我想从众多列中保留一些列,并且我想将其重复到文件末尾(多行或多行)。

这是我为此编写的代码,但它只读取一行数据。

fid = fopen ('L0512164529','r+');
num_ints = 47;
num_rows = 50;
features = struct;

format =['L%d,',repmat('%f,' , 1 , num_ints-1),'%f'];
[r_dat,l] = textscan(fid, format, num_rows);
features.name=r_dat{1};
features.bodyposfeat=[r_dat{2:end}];

fclose(fid);

每行都以一个数字开头L。文件的前两行是:

L0512164529,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.1376599,-0.4387758,0.4723490,0.751‌​9389,0.4742642,-0.8703301
L0512164529,0.0001816,0.0000005,-0.0005697,-1.0843741,0.0001816,0.0000005,-0.000‌​5697,-1.0843741,0.1433973
4

2 回答 2

0

确保您%f在格式字符串中使用了正确数量的格式说明符。看起来您可能需要使用以下格式语句:

format =['L%d,',repmat('%f,' , 1 , num_ints-2),'%f'];  %% changed to ( num_ints - 2)

假设这num_ints是列数。当我使用您的示例数据尝试您的代码时,当我将 num_ints 更改为 14 时它起作用了,因为您的示例只有 16 列,并且第一列是用L%d,. 当我将 num_ints 增加到 14 以上时,它只解析文件的 1 行。

所以要清楚,如果num_ints是列数,包括具有 L 名称的第一列,那么num_ints-2在格式字符串创建中使用应该可以工作。

于 2015-11-23T21:12:48.220 回答
0

这是另一种方法,如果您的文件中有可变数量的列。

filename = 'temp.txt'
fid = fopen(filename, 'rt');
if fid < 0
    error('Error opening file %s\n', filename); % exit point
end

desired_number_of_columns = 48;  %% 1 for the name, and 47 for the data
number_of_rows = 1385;  %% data structure won''t have this many rows, because some will be skipped

features.name=zeros(number_of_rows,1);
features.bodyposfeat=zeros(number_of_rows, desired_number_of_columns-1);

cntr = 1
while true
    tline = fgetl(fid);  %% read file one line at a time
    if ~ischar(tline), break; end; % break out of loop at end of file

    splitLine = strsplit(tline, ',');  %% separate into columns
    if (length(splitLine) ~= desired_number_of_columns)  %% check for the correct number of columns
        continue;
    end

    features.name(cntr) = str2num(splitLine{1}(2:end)); %% chop off first character and convert to number; does not check for 'L' specifically
    features.bodyposfeat(cntr, 1:desired_number_of_columns-1) = str2double(splitLine(2:end));  %% convert strings to numbers and save the rest of the columns as data
    cntr = cntr + 1;
end

%% optional - delete extra rows in the data structure that were never populated
features.name(cntr:end) = [];
features.bodyposfeat(cntr:end,:) = [];

fclose(fid)
于 2015-11-24T14:53:59.753 回答