www.gusucode.com > mbctools 工具箱 matlab 源码程序 > mbctools/xregReadDelimInfo.m

    function [Ncols, Names, Units, DelimChar, DelimAtEnd] = xregReadDelimInfo(filename, Line2)
%XREGREADDELIMINFO Get information about delimited text file
%
%  [NCOLS, NAMES, UNITS, DELIMCHAR, DELIMATEND] = XREGREADDELIMINFO(FILENAME)
%  returns the variable names and units, the delimiter character and a flag
%  indicating whether the lines end with a delimiter character or not.  If
%  there is no header line for variables names or units then these outputs
%  will be empty cell arrays.  If the delimiter char cannot be determined
%  then this output will be an empty string.
%
%  [...] = XREGREADDELIMINFO(LINE1, LINE2) will return the same information
%  given the first 2 lines of the data that is being imported.

%  Copyright 2000-2015 The MathWorks, Inc. and Ford Global Technologies, Inc.


Ncols = 0;
Names = {};
Units = {};
DelimChar = '';
DelimAtEnd = false;

if nargin==1
    fid = fopen(filename, 'rt');
    if fid==-1
        error(message('mbc:xregReadDelimInfo:FileReadError'));
    end
    Line1 = fgetl(fid);
    Line2 = fgetl(fid);
    Line3 = fgetl(fid);
    fclose(fid);
else
    Line1 = filename;
end

% Check first line to work out (a) the delimiter, (b) whether lines end in
% a delimiter or not and (c) whether there are variable names
DelimOptions = {'\t', '|', ',', ' '};
DelimIndex = 0;
for n=1:length(DelimOptions)
    if ~isempty(strfind(Line1, sprintf(DelimOptions{n})));
        DelimIndex = n;
        break
    end
end

% If we didn't find a delimiter, check the 3rd line to see if this file is
% likely to contain a single column of numbers.  In this case, any
% delimiter will do.
if DelimIndex==0
    [V, Count, Err] = sscanf(Line3, '%f', 2);
    if Count==1 && isempty(Err)
        DelimIndex = 1;
    end
end

if DelimIndex>0
    DelimChar = DelimOptions{DelimIndex};
    DelimAtEnd = strcmp(Line1(end), sprintf(DelimChar));
    
    LineFields = textscan(Line1, '%s', 'delimiter', DelimChar, 'whitespace', '');
    LineFields = LineFields{1};
    [vals, C] = xregcellstr2real(LineFields);
    
    Ncols = length(LineFields);
    if length(vals)>C
        % Some fields are non-numeric => header line
        Names = LineFields(:).';
        
        % Check second line for units
        LineFields = textscan(Line2, '%s', 'delimiter', DelimChar, 'whitespace', '');
        LineFields = LineFields{1};
        [vals, C] = xregcellstr2real(LineFields);
        if length(vals)>C && length(LineFields)==length(Names) && all(isnan(vals))
            % first line is units
            Units = LineFields(:).';
        end
    end
end