【问题标题】:MATLAB: Read in a specific order lines from a text fileMATLAB:以特定顺序从文本文件中读取行
【发布时间】:2017-09-21 13:25:23
【问题描述】:

我有一个有很多行的文本文件,每行都有一个数字。要绘制一条我想要的线,我需要阅读第 1、第 2 和第 7、第 8 和第 13、第 14 行和 s.o。我如何为此编写代码?

我从互联网上得到了一些东西,但我不知道如何使用以下代码实现我的问题。

fileID = fopen([fname 'r'],'r');
% initialize a counter
count = 0;
% keep reading the file
while 1
% get a line of text
R = fgetl(fileID);
count = count + 1;
% exit if the line is empty
if R == -1
    break;
 end
% check modulus of count for every 2nd and 11th line
if mod(count,11) == 1
    tline_2nd = R;
elseif mod(count,2) == 10
    tline_11th = R;
end
end

【问题讨论】:

  • 行是否以数字开头,或者您只需要文件中的第 [1:6:end, 2:6:end] 行?您是要在读取后立即使用行中的数据然后丢弃,还是要存储所选行的所有数据?

标签: matlab file text


【解决方案1】:

由于您想阅读 2 行并跳过 4 行,您可以执行以下操作:

编辑:这里也是存储行的代码。由于我不知道线条是什么样的,所以我将所有内容都保存在一个单元格中。

fileID = fopen(fname,'r');
% initialize a counter
readnum = 2;
readcount = 0;
skipnum = 4;
R = {}; % Make R a cell array to hold non-uniform data.
% keep reading the file
while 1
    % get a line of text
    line = fgetl(fileID);
    readcount = readcount + 1;
    % exit if the line is empty
    if line == -1
        break;
    end
    if readcount > readnum
        readcount = 1;
        for i = 1:skipnum
            line = fgetl(fileID);
            if line == -1
                break;
            end
        end
    end
    R{end+1} = line;
end

【讨论】:

  • 看起来不错,但我需要将数据保存到数组中,所以 R 必须以某种方式成为数组,我该怎么做?
  • 在不知道数据行是什么样子的情况下,我现在所能做的就是将每一行存储到一个数组中。这样就够了吗?
  • 这正是我想要的!,我的文本文件中只有数字。
  • 太棒了!如果您注册答案并投票,我将不胜感激。 :)
猜你喜欢
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多