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

    function [OK, msg, out] = xregReadDelimited(filename, out,GuiMode) %#ok<INUSD>
%XREGREADDELIMITED Read delimited text files into MBC
%
%  [OK, MSG, OUT] = XREGREADDELIMITED(FILENAME, OUT) reads delimited text
%  files into MBC.  These files can be delimited by tabs, |, commas or
%  spaces.  They may optionally contain a variable name header and units
%  header line.

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


OK = 0;
msg = '';
if nargin<3
    GuiMode = true; %#ok<NASGU>
end

% Check that the file being requested exists
if exist(filename, 'file') ~= 2
    msg = 'The file does not exist.';
    return
end

[numVars, Names, Units, DelimChar] = xregReadDelimInfo(filename);
if isempty(DelimChar)
    msg = 'Unable to determine the delimiter character.';
    return
end

numHeaders = 0;
if ~isempty(Names)
    out.varNames = Names;
    numHeaders = numHeaders + 1;
else
    out.varNames = repmat({'VAR'}, 1, numVars);
end
if ~isempty(Units)
    out.varUnits = Units;
    numHeaders = numHeaders + 1;
else
    out.varUnits = repmat({''}, 1, numVars);
end

fid = fopen(filename, 'rt');

% Read a byte and rewind.  This prevents problems later with some files
% returning empty in the later textscan operation.
fread(fid,1);
frewind(fid);

for n = 1:numHeaders
    fgets(fid);
end

% Read each line into a separate string and then process them separately.
% Trailing empty lines are ignored by textscan
Lines = textscan(fid, '%s', -1, 'delimiter', '', 'whitespace', '');
fclose(fid);

try
    Lines = cellfun(@(x) iSplitLine(x, DelimChar, numVars), Lines{1}, 'UniformOutput', false);
catch ME
    [mnemonic, ~, msg] = mbcGetLastError(ME);
    if strcmp(mnemonic, 'NonNumericCharacter')
        % Use message that was stripped out by mbcGetLastError
        return
    else
        rethrow(ME);
    end
end

% Check that there are no lines that are still too short
L = cellfun('length', Lines);
if any(L~=numVars)
    msg = sprintf('Each line of "%s" must have the same number of data points.',filename);
    return
end

data = [Lines{:}].';

% Remove rows that are all NaNs
out.data = data(~all(isnan(data),2),:);
OK = 1;


function Values = iSplitLine(Line, DelimChar, numVars)

try
    % Split line at the delimiter.  Strings that cannot be converted to
    % numbers are caught as an error
    Values = textscan(Line, '%n', -1, 'delimiter', DelimChar, 'ReturnOnError', false);
catch
    error(message('mbc:xregReadDelimited:NonNumericCharacter'));
end

Values = Values{1};
if length(Values)<numVars
    % Allow lines that are too short by one: this allows for lines that end
    % in an empty entry and haven't had their delimiter read correctly.  We
    % could pad any number of missing delimiters but choose to expose these
    % as corrupt files to the user rather than quietly introduce too many NaNs.
    Values(end+1) = NaN;
end