如果在.txt文件中移动行,则导入具有readtable的表

时间:2018-02-08 09:14:57

标签: matlab import delimiter tab-delimited

我有一张看起来像这样的表

x x x x x x 
x x
y y y y y y
y y
z z z z z z 
z z 

我想使用readtable导入它,以便所有x都在一行中,所有y在下一行中等等。换句话说,在.txt文件中,最后两个内容是假设的在一行中转移到下一行。我想我需要在DelimitedTextImportOptions中改变一些东西,但我无法弄清楚到底是什么。

如果有人可以帮助我,我会很高兴,非常感谢你!

2 个答案:

答案 0 :(得分:1)

如果要求使用readtable,一个选项是将原始文件转换为新格式,然后将readtable应用于新文件。

以下是可在以下示例中使用的文件in.txt的示例内容:

1 2 3 abc 5 6
7 8
3 4 5 def 7 8
9 0
9 1 0 ghi 3 2
1 4

以下是代码:

% FIRST, TRANSFORM THE INPUT FILE INTO A FILE WHERE THE SPLIT LINES ARE
% COMBINED INTO SINGLE LINES

% open input and output files
in = fopen('in.txt', 'r');
out = fopen('out.txt', 'w');

% read the first line of the input file
currline = fgetl(in);

% while we haven't reached the end of the file
while ~isequal(currline, -1)

    % read the following line of the input file
    currline_append = fgetl(in);
    % ... if it doesn't exist, throw an error; the file is not as expected
    if isequal(currline_append, -1)
        error('Bad file');
    end

    % print this pair of lines to the output file as a single line.
    % Note: if using Windows Notepad or similar application to read the
    % file, you may want to replace '\n' by '\r\n' in the format string
    fprintf(out, '%s %s\n', currline, currline_append);

    % get the next line of the input file
    currline = fgetl(in);
end

% close input and output files
fclose(in);
fclose(out);

% NEXT, READ THE TABLE FROM THE OUTPUT FILE

t = readtable('out.txt');

答案 1 :(得分:0)

实际上,如果你的文字文件形状如你所描述的那样完全 STRICTLY (每一行都有相同数量的元素,其中两行溢出到下一行),你可以很容易地阅读它:

fid = fopen('data.txt','r');
data = textscan(fid,'%d','CollectOutput',true);
fclose(fid);

data_inner = data{1,1};
cols = 8; % predefined number of elements per row
rows = numel(data_inner) / cols;

C = reshape(data_inner.',cols,rows).';

输入示例:

1 2 3 4 5 6
7 8
2 3 4 5 6 7
8 9
3 4 5 6 7 8
9 10

输出示例:

C =
    1    2    3    4    5    6    7    8
    2    3    4    5    6    7    8    9
    3    4    5    6    7    8    9   10

完成此操作后,矩阵可以轻松转换为表格,如下所示:

T = array2table(C)

T =

    C1    C2    C3    C4    C5    C6    C7    C8
    __    __    __    __    __    __    __    __

    1     2     3     4     5     6     7      8
    2     3     4     5     6     7     8      9
    3     4     5     6     7     8     9     10