Code covered by the BSD License  

Highlights from
textfile

Be the first to rate this file! 4 Downloads (last 30 days) File Size: 2.31 KB File ID: #29477

textfile

by Ben Mitch

 

21 Nov 2010 (Updated 22 Nov 2010)

Provides a one-call interface to read/write flat text files or line-based text files.

| Watch this File

File Information
Description

This convenience function provides one-call read/write access to a flat text or line-based text file using calls of the following form.

content = textfile(filename);
textfile(filename, content);

The content can be returned as a char array, or a cell array of lines in the file. Some additional options are provided (see help).

MATLAB release MATLAB 7.10 (2010a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (2)
23 Nov 2010 Jan Simon

This program is useful for a very frequently used job.
The documentation is exact and descriptive, but does not follow the standard design of Matlab:
  function XY
  % H1-line
  % Help text...
This impedes e.g. LOOKFOR. The documentatoion mentions author and date. The code is well commented. Inputs are checked.

"~exist('arg1')" is not efficient to test, if an input was defined: besides variables, it accepts "arg1.m", "arg1.p", "arg1.mex...", "arg1.mdl", a folder or java class called "arg1" anywhere in the Matlab path also! Therefore it is horribly slow, if "arg1" is not a variable. Either use "exist('arg1', 'var')", or NARGIN.
The conversion from a cell string to a string without pre-allocation gets very slow for large data. SPRINTF('%s\n', content{:}) is much faster.
Pre-allocation would be a good idea for splitting a read text to a cell string also: content = cell(N, 1);
Finding CHAR(10) using "lf = find(str == 10);" has drawbacks: 1) It compares different types. 2) It creates a temporary LOGICAL array. Therefore this is ~30% faster for a 10kB string: "lf = find(str == char(10));", and "lf = findstr(str, char(10))" consumes just the half processing time. Same for "content(content ~= 13);".
Nevertheless, TEXTSCAN(fid, '%s', 'delimiter', '\n') is much more efficient to read a file into a cell string, so there is no need to reinvent the wheel.
Perhaps these ideas help to improve the efficiency of this submission.

23 Nov 2010 Ben Mitch

Thanks Jan, have copied your text into my TODO file :)

Please login to add a comment or rating.
Updates
22 Nov 2010

Linux implementation was broken, now is fixed.

Tag Activity for this File
Tag Applied By Date/Time
file Ben Mitch 22 Nov 2010 12:10:04
text file Ben Mitch 22 Nov 2010 12:10:04
read Ben Mitch 22 Nov 2010 12:10:06
write Ben Mitch 22 Nov 2010 12:10:06

Contact us at files@mathworks.com