Code covered by the BSD License  

Highlights from
*.txt read

  • txtread; this function reads a tab delimited txt file into a cell array. The file to be imported can have 1 or
  • View all files
image thumbnail
from *.txt read by Giuliano Langella
This function reads a tab delimited txt file into a cell array.

txtread;
function [varargout] = txtread;
% this function reads a tab delimited txt file into a cell array. The file to be imported can have 1 or
% more both column and/or row header lines.


[FileName, PathName] = uigetfile({'*.txt','Text file [tab delimited] (*.txt)'; '*.xls','Excel (*.xls)'; '*.*','All Files (*.*)'}, 'Import tab delimited txt file', pwd);
varargout{2} = FileName;
newData = importdata(strcat(PathName, FileName));

% Create new variables in the base workspace from those fields.
vars = fieldnames(newData);

% check how many column and row header lines are in the file
s1 = size(newData.(vars{2}));
if isempty(find(s1==1))
    d = diag(newData.(vars{2}));
    for i = 1:size(d,1)
        if isempty(find(not(isempty(d{i}))))
            empty(i) = 0;
        else
            empty(i) = find(not(isempty(d{i})));
        end
    end
end

%-data
table = newData.(vars{1});
header = newData.(vars{2});
varargout{1} = cell(s1(1), s1(2));
if      s1(1) == 1 & s1(2) ~= 1
    %-cell array: [header; data] ==> vert cat ==> col header
    varargout{1} = [header; num2cell(table)];
elseif  s1(1) ~= 1 & s1(2) == 1
    %-cell array: [header data] ==> hor cat ==> row header
    varargout{1} = [header num2cell(table)];
elseif  s1(1) > 1 & s1(2) > 1
    %cell array: mixed hor and vert cat
    s2 = size(table);
    s = s1-s2;
    varargout{1} = [header(1:s(1),:); header(s(1)+1:end,1:s(2)), num2cell(table)];
end

Contact us at files@mathworks.com