Skip to content

Instantly share code, notes, and snippets.

@KubaO
Last active February 16, 2018 14:02
Show Gist options
  • Save KubaO/2b9896d72d3375c1fb53970d4961b7a7 to your computer and use it in GitHub Desktop.
Save KubaO/2b9896d72d3375c1fb53970d4961b7a7 to your computer and use it in GitHub Desktop.
An Octave universal delimited file cell reader.
## Author: voithos on so
## Url: https://stackoverflow.com/a/8319848/1329652
function varargout = coltextread(fname, delim)
% Initialize the variable output argument
varargout = cell(nargout, 1);
% Initialize elements of the cell array to nested cell arrays
% This syntax is due to {:} producing a comma-separated
[varargout{:}] = deal(cell());
fid = fopen(fname, 'r');
while true
% Get the current line
ln = fgetl(fid);
% Stop if EOF
if ln == -1
break;
endif
% Split the line string into components and parse numbers
elems = strsplit(ln, delim);
nums = str2double(elems);
nans = isnan(nums);
% Special case of all strings (header line)
if all(nans)
continue;
endif
% Find the indices of the NaNs
% (i.e. the indices of the strings in the original data)
idxnans = find(nans);
% Assign each corresponding element in the current line
% into the corresponding cell array of varargout
for i = 1:nargout
% Detect if the current index is a string or a num
if any(ismember(idxnans, i))
varargout{i}{end+1} = elems{i};
else
varargout{i}{end+1} = nums(i);
endif
endfor
endwhile
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment