从文件中读取数据:通过文件中的空行保持分离

时间:2014-06-23 14:25:31

标签: matlab matrix

我可以使用此代码从x制作一个矩阵ydata.dat,其中包含2列:

load data.dat
x=data(:,1);
y=data(:,2);

如果我想制作矩阵x1x2,... xn以及与y相同的内容, 其中x1x2基于文件data.dat中空行的分隔:

54.510  1.420
55.294  1.819
55.859  1.935
55.999  2.381

9.017   1.600
9.518   1.916
9.868   2.217
9.896   2.368
10.113  2.533
10.424  2.552

....    ...

根据这个数据示例,我希望

x1=[54.510;55.294;55.859;55.999]
x2=[9.017;9.518;9.868;9.896;10.113;10.424]
y1=[1.420;1.819;1.935;2.381]
y2=[1.600;1.916;2.217;2.368;2.533;2.552]

1 个答案:

答案 0 :(得分:0)

您可以使用fgets来读取文件中的数据。假设您的文件名为test.dat
(有关功能的说明,请参阅注释)

% introduce a counter for all the 'blocks in the file'
block = 1;
% initialize empty vectors for x and y
x = [];
y = [];

% open the file (in this case 'test.dat')
file = fopen('test.dat');

% read the first line of the file
tline = fgets(file);

% continue as long as there are lines in the file
while ischar(tline)

    % fgets returs a string, convert to float to process:
    q = str2num(tline);

    % if q is empty, we have a blank line, otherwise, append the values to 
    % x and y

    if ~isempty(q)
        x(end+1) = q(1);
        y(end+1) = q(2);
    else

    % if there is a blank line, write x and y to a cell X and Y
    % you need a cell here, because the number of elements per block may 
    % differ

        X{block} = x;
        Y{block} = y;

    % advance the block counter

        block = block + 1;

    % clear and re-initialize x and y - this is necessary because the next
    % block may contain less values. you do not want artifacts.

        clear x y
        x = [];
        y = [];
    end

    % read the next line

    tline = fgets(file);

    % at the end of the file, fgets returns not a string but a number, -1
    % in this case, assign x and y to X and Y
    % no need to increment block, because you are at the end of the file

    if tline == -1
        X{block} = x;
        Y{block} = y;
    end

end

% close the file once all operations are done

fclose(file);

您现在有一个单元格X和一个单元格Y,其中包含您文件中的数据。例如。

X{1} = 

  Columns 1 through 2

                 54.51                    55.294

  Columns 3 through 4

                55.859                    55.999

我知道您不会使用此方法获取名为x1x2,... xn的变量。但是,我认为单元格X{1}X{2},... X{n}比单个变量更容易生成,填充和处理。