Textread - Read data from text file; write to multiple outputs



textread - Read data from text file; write to multiple outputs

|Note   textread is not recommended. Use textscan to read data from a text file. |

Graphical Interface

As an alternative to textread, use the Import Wizard. To activate the Import Wizard, select Import Data from the File menu.

Syntax

[A,B,C,...] = textread('filename','format')

[A,B,C,...] = textread('filename','format',N)

[...] = textread(...,'param','value',...)

Description

[A,B,C,...] = textread('filename','format') reads data from the file 'filename' into the variables A,B,C, and so on, using the specified format, until the entire file is read. The filename and format inputs are strings, each enclosed in single quotes. textread is useful for reading text files with a known format. textread handles both fixed and free format files.

|Note   When reading large text files, reading from a specific point in a file, or reading file data into a cell array rather than multiple outputs, |

|you might prefer to use the textscan function. |

textread matches and converts groups of characters from the input. Each input field is defined as a string of non-white-space characters that extends to the next white-space or delimiter character, or to the maximum field width. Repeated delimiter characters are significant, while repeated white-space characters are treated as one.

The format string determines the number and types of return arguments. The number of return arguments is the number of items in the format string. The format string supports a subset of the conversion specifiers and conventions of the C language fscanf routine. Values for the format string are listed in the table below. White-space characters in the format string are ignored.

|format |Action |Output |

|Literals |Ignore the matching characters. For example, in a file that has Dept followed by a number (for department |None |

|(ordinary characters)|number), to skip the Dept and read only the number, use 'Dept' in the format string. | |

|%d |Read a signed integer value. |Double array |

|%u |Read an integer value. |Double array |

|%f |Read a floating-point value. |Double array |

|%s |Read a white-space or delimiter-separated string. |Cell array of |

| | |strings |

|%q |Read a double quoted string, ignoring the quotes. |Cell array of |

| | |strings |

|%c |Read characters, including white space. |Character array |

|%[...] |Read the longest string containing characters specified in the brackets. |Cell array of |

| | |strings |

|%[^...] |Read the longest nonempty string containing characters that are not specified in the brackets. |Cell array of |

| | |strings |

|%*... |Ignore the matching characters specified by *. |No output |

|instead of % | | |

|%w... |Read field width specified by w. The %f format supports %w.pf, where w is the field width and p is the precision.| |

|instead of % | | |

[A,B,C,...] = textread('filename','format',N) reads the data, reusing the format string N times, where N is an integer greater than zero. If N is smaller than zero, textread reads the entire file.

[...] = textread(...,'param','value',...) customizes textread using param/value pairs, as listed in the table below.

|param |value |Action |

|bufsize |Positive integer |Specifies the maximum string length, in bytes. Default is 4095. |

|commentstyle |matlab |Ignores characters after %. |

|commentstyle |shell |Ignores characters after #. |

|commentstyle |c |Ignores characters between /* and */. |

|commentstyle |c++ |Ignores characters after //. |

|delimiter |One or more characters |Act as delimiters between elements. Default is none. |

|emptyvalue |Scalar double |Value given to empty cells when reading delimited files. Default is 0. |

|endofline |Single character or '\r\n' |Character that denotes the end of a line. |

| | |Default is determined from file |

|expchars |Exponent characters |Default is eEdD. |

|headerlines |Positive integer |Ignores the specified number of lines at the beginning of the file. |

|whitespace |Any from the list below: |Treats vector of characters as white space. Default is ' \b\t'. |

| |' ' |Space | |

| |\b |Backspace | |

| |\n |Newline | |

| |\r |Carriage return | |

| |\t |Horizontal tab | |

|Note   When textread reads a consecutive series of whitespace values, it treats them as one white space. When it reads a consecutive series of |

|delimiter values, it treats each as a separate delimiter. |

Remarks

If you want to preserve leading and trailing spaces in a string, use the whitespace parameter as shown here:

textread('myfile.txt', '%s', 'whitespace', '')

ans =

' An example of preserving spaces '

Examples

Example 1 — Read All Fields in Free Format File Using %

The first line of mydata.dat is

Sally Level1 12.34 45 Yes

Read the first line of the file as a free format file using the % format.

[names, types, x, y, answer] = textread('mydata.dat', ...

'%s %s %f %d %s', 1)

returns

names =

'Sally'

types =

'Level1'

x =

12.34000000000000

y =

45

answer =

'Yes'

Example 2 — Read as Fixed Format File, Ignoring the Floating Point Value

The first line of mydata.dat is

Sally Level1 12.34 45 Yes

Read the first line of the file as a fixed format file, ignoring the floating-point value.

[names, types, y, answer] = textread('mydata.dat', ...

'%9c %5s %*f %2d %3s', 1)

returns

names =

Sally

types =

'Level1'

y =

45

answer =

'Yes'

%*f in the format string causes textread to ignore the floating point value, in this case, 12.34.

Example 3 — Read Using Literal to Ignore Matching Characters

The first line of mydata.dat is

Sally Type1 12.34 45 Yes

Read the first line of the file, ignoring the characters Type in the second field.

[names, typenum, x, y, answer] = textread('mydata.dat', ...

'%s Type%d %f %d %s', 1)

returns

names =

'Sally'

typenum =

1

x =

12.34000000000000

y =

45

answer =

'Yes'

Type%d in the format string causes the characters Type in the second field to be ignored, while the rest of the second field is read as a signed integer, in this case, 1.

Example 4 — Specify Value to Fill Empty Cells

For files with empty cells, use the emptyvalue parameter. Suppose the file data.csv contains:

1,2,3,4,,6

7,8,9,,11,12

Read the file using NaN to fill any empty cells:

data = textread('data.csv', '', 'delimiter', ',', ...

'emptyvalue', NaN);

Example 5 — Read M-File into a Cell Array of Strings

Read the file fft.m into cell array of strings.

file = textread('fft.m', '%s', 'delimiter', '\n', ...

'whitespace', '');

See Also

textscan, dlmread, csvread, fscanf

|  |[pic] |

fscanf - Read formatted data from a text file

Syntax

A = fscanf(fid, format)

[A,count] = fscanf(fid, format, size)

Description

|Note   fscanf reads text files. To read binary files, use fread. |

A = fscanf(fid, format) reads data from the file specified by fid, converts it according to the specified format string, and returns it in matrix A. Argument fid is an integer file identifier obtained from fopen. format is a string specifying the format of the data to be read. See "Remarks" for details.

[A,count] = fscanf(fid, format, size) reads the amount of data specified by size, converts it according to the specified format string, and returns it along with a count of values successfully read. size is an argument that determines how much data is read. Valid options are

|n |Read at most n numbers, characters, or strings. |

|inf |Read to the end of the file. |

|[m,n] |Read at most (m*n) numbers, characters, or strings. Fill a matrix of at most m rows in column order. n can be inf, but m cannot. |

Characteristics of the output matrix A depend on the values read from the file and on the size argument. If fscanf reads only numbers, and if size is not of the form [m,n], matrix A is a column vector of numbers. If fscanf reads only characters or strings, and if size is not of the form [m,n], matrix A is a row vector of characters. See the Remarks section for more information.

fscanf differs from its C language namesake fscanf() in an important respect — it is vectorized to return a matrix argument. The format string is cycled through the file until the first of these conditions occurs:

▪ The format string fails to match the data in the file

▪ The amount of data specified by size is read

▪ The end of the file is reached

Remarks

When the MATLAB software reads a specified file, it attempts to match the data in the file to the format string. If a match occurs, the data is written into the output matrix. If a partial match occurs, only the matching data is written to the matrix, and the read operation stops.

The format string consists of ordinary characters and/or conversion specifications. Conversion specifications indicate the type of data to be matched and involve the character %, optional width fields, and conversion characters, organized as shown below.

[pic]

Add one or more of these characters between the % and the conversion character:

|An asterisk (*) |Skip over the matched value. If %*d, then the value that matches d is ignored and is not stored. |

|A digit string |Maximum field width. For example, %10d. |

|A letter |The size of the receiving object, for example, h for short, as in %hd for a short integer, or l for long, as in %ld for a long integer,|

| |or %lg for a double floating-point number. |

Valid conversion characters are

|%c |Sequence of characters; number specified by field width |

|%d |Base 10 integers |

|%e, %f, %g |Floating-point numbers |

|%i |Defaults to base 10 integers. Data starting with 0 is read as base 8. Data starting with 0x or 0X is read as base 16. |

|%o |Signed octal integer |

|%s |A series of non-white-space characters |

|%u |Unsigned decimal |

|%x |Signed hexadecimal integer |

|[...] |Sequence of characters (scanlist) |

Format specifiers %e, %f, and %g accept the text 'inf', '-inf', 'nan', and '-nan'. This text is not case sensitive. The fscanf function converts these to the numeric representation of Inf, -Inf, NaN, and -NaN.

Use %c to read space characters or %s to skip all white space. MATLAB skips over any ordinary characters that are used in the format specifier (see Example 2 below).

MATLAB reads characters using the encoding scheme associated with the file. See fopen for more information. If the format string contains ordinary characters, MATLAB matches each of those characters with a character read from the file after converting both to the MATLAB internal representation of characters.

For more information about format strings, refer to the scanf() and fscanf() routines in a C language reference manual.

Output Characteristics: Only Numeric Values Read

Format characters that cause fscanf to read numbers from the file are %d, %e, %f, %g, %i, %o, %u, and %x. When fscanf reads only numbers from the file, the elements of the output matrix A are numbers.

When there is no size argument or the size argument is inf, fscanf reads to the end of the file. The output matrix is a column vector with one element for each number read from the input.

When the size argument is a scalar n, fscanf reads at most n numbers from the file. The output matrix is a column vector with one element for each number read from the input.

When the size argument is a matrix [m,n], fscanf reads at most (m*n) numbers from the file. The output matrix contains at most m rows and n columns. fscanf fills the output matrix in column order, using as many columns as it needs to contain all the numbers read from the input. Any unfilled elements in the final column contain zeros.

Output Characteristics: Only Character Values Read

The format characters that cause fscanf to read characters and strings from the file are %c and %s. When fscanf reads only characters and strings from the file, the elements of the output matrix A are characters. When fscanf reads a string from the input, the output matrix includes one element for each character in the string.

When there is no size argument or the size argument is inf, fscanf reads to the end of the file. The output matrix is a row vector with one element for each character read from the input.

When the size argument is a scalar n, fscanf reads at most n character or string values from the file. The output matrix is a row vector with one element for each character read from the input. When string values are read from the input, the output matrix can contain more than n columns.

When the size argument is a matrix [m,n], fscanf reads at most (m*n) character or string values from the file. The output matrix contains at most m rows. fscanf fills the output matrix in column order, using as many columns as it needs to contain all the characters read from the input. When string values are read from the input, the output matrix can contain more than n columns. Any unfilled elements in the final column contain char(0).

Output Characteristics: Both Numeric and Character Values Read

When fscanf reads a combination of numbers and either characters or strings from the file, the elements of the output matrix A are numbers. This is true even when a format specifier such as '%*d %s' tells MATLAB to ignore numbers in the input string and output only characters or strings. When fscanf reads a string from the input, the output matrix includes one element for each character in the string. All characters are converted to their numeric equivalents in the output matrix.

When there is no size argument or the size argument is inf, fscanf reads to the end of the file. The output matrix is a column vector with one element for each character read from the input.

When the size argument is a scalar n, fscanf reads at most n number, character, or string values from the file. The output matrix contains at most n rows. fscanf fills the output matrix in column order, using as many columns as it needs to represent all the numbers and characters read from the input. When string values are read from the input, the output matrix can contain more than one column. Any unfilled elements in the final column contain zeros.

When the size argument is a matrix [m,n], fscanf reads at most (m*n) number, character, or string values from the file. The output matrix contains at most m rows. fscanf fills the output matrix in column order, using as many columns as it needs to represent all the numbers and characters read from the input. When string values are read from the input, the output matrix can contain more than n columns. Any unfilled elements in the final column contain zeros.

|Note   This section applies only when fscanf actually reads a combination of numbers and either characters or strings from the file. Even if the |

|format string has both format characters that would result in numbers (such as %d) and format characters that would result in characters or strings |

|(such as %s), fscanf might actually read only numbers or only characters or strings. If fscanf reads only numbers, see Output Characteristics: Only |

|Numeric Values Read. If fscanf reads only characters or strings, see Output Characteristics: Only Character Values Read. |

Examples

Example 1

An example in fprintf generates a text file called exp.txt that looks like this:

0.00 1.00000000

0.10 1.10517092

...

1.00 2.71828183

Read this file back into a two-column MATLAB matrix:

fid = fopen('exp.txt', 'r');

a = fscanf(fid, '%g %g', [2 inf]) % It has two rows now.

a = a';

fclose(fid)

Example 2

Start with a file temp.dat that contains temperature readings:

78°F 72°F 64°F 66°F 49°F

Open the file using fopen and read it with fscanf. If you include ordinary characters (such as the degree (°) and Farrenheit (F) symbols used here) in the conversion string, fscanf skips over those characters when reading the string:

fid = fopen('temps.dat', 'r');

degrees = char(176)

degrees =

°

fscanf(fid, ['%d' degrees 'F'])

ans =

78

72

64

66

49

fgets - Read line from file, keeping newline characters

Syntax

tline = fgets(fid)

tline = fgets(fid, nchar)

Description

tline = fgets(fid) returns the next line of the file associated with file identifier fid. (For a description of fid, see fopen.) If the line contains only the end-of-file marker, fgets returns -1.

The returned string tline includes the newline characters associated with the text line. To obtain the string without the newline characters, use fgetl.

tline = fgets(fid, nchar) returns at most nchar characters of the next line. No additional characters are read after the newline characters or an end-of-file marker.

Remarks

fgets reads characters using the encoding scheme associated with the file. For more information, see fopen.

If your file does not contain newline characters, fgets may take a long time to execute.

After fgets reads a newline character, it checks the next character for the end-of-file marker. If the next character is the end-of-file marker, fgets sets the end-of-file indicator used by the feof function. However, in this case, fgets returns the text from the line, and does not return -1. For more information, see fgetl.

fread - Read binary data from file

Syntax

A = fread(fid)

A = fread(fid, count)

A = fread(fid, count, precision)

A = fread(fid, count, precision, skip)

A = fread(fid, count, precision, skip, machineformat)

[A, count] = fread(...)

Description

|Note   fread reads binary files. To read text files, use fscanf. |

A = fread(fid) reads data in binary format from the file specified by fid into matrix A. Open the file using fopen before calling fread. The fid argument is the integer file identifier obtained from the fopen operation. The MATLAB software reads the file from beginning to end, and then positions the file pointer at the end of the file (see feof for details).

A = fread(fid, count) reads the number of elements specified by count. At the end of the fread, MATLAB sets the file pointer to the next byte to be read. A subsequent fread will begin at the location of the file pointer. See Specifying the Number of Elements, below.

|Note   In the following syntaxes, the count and skip arguments are optional. For example, fread(fid, precision) is a valid syntax. |

A = fread(fid, count, precision) reads the file according to the data format specified by the string precision. This argument commonly contains a data type specifier such as int or float, followed by an integer giving the size in bits. See Specifying precision and Specifying Output Format, below.

A = fread(fid, count, precision, skip) includes an optional skip argument that specifies the number of bytes to skip after each precision value is read. If precision specifies a bit format like 'bitN' or 'ubitN', the skip argument is interpreted as the number of bits to skip. See Specifying a Skip Value, below.

A = fread(fid, count, precision, skip, machineformat) treats the data read as having a format given by machineformat. You can obtain the machineformat argument from the output of the fopen function. See fopen for possible values for machineformat.

[A, count] = fread(...) returns the data read from the file in A, and the number of elements successfully read in count.

Specifying the Number of Elements

Valid options for count are

|n |Reads n elements into a column vector. |

|inf |Reads to the end of the file, resulting in a column vector containing the same number of elements as are in the file. If using inf results in |

| |an "out of memory" error, specify a numeric count value. |

|[m,n] |Reads enough elements to fill an m-by-n matrix, filling in elements in column order, padding with zeros if the file is too small to fill the |

| |matrix. n can be specified as inf, but m cannot. |

Specifying precision

Any of the strings in the following table, either the MATLAB version or their C or Fortran equivalent, can be used for precision. If precision is not specified, MATLAB uses the default, which is 'uint8'.

|MATLAB |C or Fortran |Interpretation |

|'schar' |'signed char' |Signed integer; 8 bits |

|'uchar' |'unsigned char' |Unsigned integer; 8 bits |

|'int8' |'integer*1' |Integer; 8 bits |

|'int16' |'integer*2' |Integer; 16 bits |

|'int32' |'integer*4' |Integer; 32 bits |

|'int64' |'integer*8' |Integer; 64 bits |

|'uint8' |'integer*1' |Unsigned integer; 8 bits |

|'uint16' |'integer*2' |Unsigned integer; 16 bits |

|'uint32' |'integer*4' |Unsigned integer; 32 bits |

|'uint64' |'integer*8' |Unsigned integer; 64 bits |

|'float32' |'real*4' |Floating-point; 32 bits |

|'float64' |'real*8' |Floating-point; 64 bits |

|'double' |'real*8' |Floating-point; 64 bits |

The following platform-dependent formats are also supported, but they are not guaranteed to be the same size on all platforms.

|MATLAB |C or Fortran |Interpretation |

|'char' |'char*1' |Character |

|'short' |'short' |Integer; 16 bits |

|'int' |'int' |Integer; 32 bits |

|'long' |'long' |Integer; 32 or 64 bits |

|'ushort' |'unsigned short' |Unsigned integer; 16 bits |

|'uint' |'unsigned int' |Unsigned integer; 32 bits |

|'ulong' |'unsigned long' |Unsigned integer; 32 or 64 bits |

|'float' |'float' |Floating-point; 32 bits |

|Note   If the format is 'char' or 'char*1', MATLAB reads characters using the encoding scheme associated with the file. See fopen for more |

|information. |

The following formats map to an input stream of bits rather than bytes.

|MATLAB |C or Fortran |Interpretation |

|'bitN' |- |Signed integer; N bits (1 ≤ N ≤ 64) |

|'ubitN' |- |Unsigned integer; N bits (1 ≤ N ≤ 64) |

Specifying Output Format

By default, numeric and character values are returned in class double arrays. To return these values stored in classes other than double, create your format argument by first specifying your source format, then following it with the characters "=>," and finally specifying your destination format. You are not required to use the exact name of a MATLAB class type for destination. (See class for details). fread translates the name to the most appropriate MATLAB class type. If the source and destination formats are the same, the following shorthand notation can be used.

*source

which means

source=>source

For example, '*uint16' is the same as 'uint16=>uint16'.

|Note   You can also use the *source notation with an input stream that is specified as a number of bits (e.g., bit4 or ubit18). MATLAB translates |

|this into an output type that is a signed or unsigned integer (depending on the input type), and that is large enough to hold all of the bits in the |

|source format. For example, *ubit18 does not translate to ubit18=>ubit18, but instead to ubit18=>uint32. |

This table shows some example precision format strings.

|'uint8=>uint8' |Read in unsigned 8-bit integers and save them in an unsigned 8-bit integer array. |

|'*uint8' |Shorthand version of the above. |

|'bit4=>int8' |Read in signed 4-bit integers packed in bytes and save them in a signed 8-bit array. Each 4-bit integer becomes an 8-bit |

| |integer. |

|'double=>real*4' |Read in doubles, convert, and save as a 32-bit floating-point array. |

Specifying a Skip Value

When skip is used, the precision string can contain a positive integer repetition factor of the form 'N*', which prefixes the source format specification, such as '40*uchar'.

|Note   Do not confuse the asterisk (*) used in the repetition factor with the asterisk used as precision format shorthand. The format string |

|'40*uchar' is equivalent to '40*uchar=>double', not '40*uchar=>uchar'. |

When skip is specified, fread reads in, at most, a repetition factor number of values (default is 1), skips the amount of input specified by the skip argument, reads in another block of values, again skips input, and so on, until count number of values have been read. If a skip argument is not specified, the repetition factor is ignored. Use the repetition factor with the skip argument to extract data in noncontiguous fields from fixed-length records.

Remarks

If the input stream is bytes and fread reaches the end of file (see feof) in the middle of reading the number of bytes required for an element, the partial result is ignored. However, if the input stream is bits, then the partial result is returned as the last value. If an error occurs before reaching the end of file, only full elements read up to that point are used.

Examples

Example 1

The file alphabet.txt contains the 26 letters of the English alphabet, all capitalized. Open the file for read access with fopen, and read the first five elements into output c. Because a precision has not been specified, MATLAB uses the default precision of uint8, and the output is numeric:

fid = fopen('alphabet.txt', 'r');

c = fread(fid, 5)'

c =

65 66 67 68 69

fclose(fid);

This time, specify that you want each element read as an unsigned 8-bit integer and output as a character. (Using a precision of 'char=>char' or '*char' will produce the same result):

fid = fopen('alphabet.txt', 'r');

c = fread(fid, 5, 'uint8=>char')'

c =

ABCDE

fclose(fid);

When you leave out the optional count argument, MATLAB reads the file to the end, A through Z:

fid = fopen('alphabet.txt', 'r');

c = fread(fid, '*char')'

c =

ABCDEFGHIJKLMNOPQRSTUVWXYZ

fclose(fid);

The fopen function positions the file pointer at the start of the file. So the first fread in this example reads the first five elements in the file, and then repositions the file pointer at the beginning of the next element. For this reason, the next fread picks up where the previous fread left off, at the character F.

fid = fopen('alphabet.txt', 'r');

c1 = fread(fid, 5, '*char');

c2 = fread(fid, 8, '*char');

c3 = fread(fid, 5, '*char');

fclose(fid);

sprintf('%c', c1, ' * ', c2, ' * ', c3)

ans =

ABCDE * FGHIJKLM * NOPQR

Skip two elements between each read by specifying a skip argument of 2:

fid = fopen('alphabet.txt', 'r');

c = fread(fid, '*char', 2); % Skip 2 bytes per read

fclose(fid);

sprintf('%c', c)

ans =

ADGJMPSVY

Example 2

This command displays the complete M-file containing this fread help entry:

type fread.m

To simulate this command using fread, enter the following:

fid = fopen('fread.m', 'r');

F = fread(fid, '*char')';

fclose(fid);

In the example, the fread command assumes the default size, 'inf', and precision '*char' (the same as 'char=>char'). fread reads the entire file. To display the result as readable text, the column vector is transposed to a row vector.

Example 3

As another example,

s = fread(fid, 120, '40*uchar=>uchar', 8);

reads in 120 bytes in blocks of 40, each separated by 8 bytes. Note that the class type of s is 'uint8' since it is the appropriate class corresponding to the destination format 'uchar'. Also, since 40 evenly divides 120, the last block read is a full block, which means that a final skip is done before the command is finished. If the last block read is not a full block, then fread does not finish with a skip.

See fopen for information about reading big and little-endian files.

Example 4

Invoke the fopen function with just an fid input argument to obtain the machine format for the file. You can see that this file was written in IEEE floating point with little-endian byte ordering ('ieee-le') format:

fid = fopen('A1.dat', 'r');

[fname, mode, mformat] = fopen(fid);

mformat

mformat =

ieee-le

Use the MATLAB format function (not related to the machine format type) to have MATLAB display output using hexadecimal:

format hex

Now use the machineformat input with fread to read the data from the file using the same format:

x = fread(fid, 6, 'uint64', 'ieee-le')

x =

4260800000002000

0000000000000000

4282000000180000

0000000000000000

42ca5e0000258000

42f0000464d45200

fclose(fid);

Change the machine format to IEEE floating point with big-endian byte ordering ('ieee-be') and verify that you get different results:

fid = fopen('A1.dat', 'r');

x = fread(fid, 6, 'uint64', 'ieee-be')

x =

4370000008400000

0000000000000000

4308000200100000

0000000000000000

4352c0002f0d0000

43c022a6a3000000

fclose(fid);

Example 5

This example reads some Japanese text from a file that uses the Shift-JIS character encoding scheme. It creates a string of Unicode® characters, str, and displays the string. Note that the computer must be configured to display Japanese (e.g., a Japanese machine running the Windows operating system) for the output of disp(str) to be correct.

fid = fopen('japanese.txt', 'r', 'n', 'Shift_JIS');

str = fread(fid, '*char')';

fclose(fid);

disp(str);

dlmread - Read ASCII-delimited file of numeric data into matrix

Graphical Interface

As an alternative to dlmread, use the Import Wizard. To activate the Import Wizard, select Import data from the File menu.

Syntax

M = dlmread(filename)

M = dlmread(filename, delimiter)

M = dlmread(filename, delimiter, R, C)

M = dlmread(filename, delimiter, range)

Description

M = dlmread(filename) reads from the ASCII-delimited numeric data file filename to output matrix M. The filename input is a string enclosed in single quotes. The delimiter separating data elements is inferred from the formatting of the file. Comma (,) is the default delimiter.

M = dlmread(filename, delimiter) reads numeric data from the ASCII-delimited file filename, using the specified delimiter. Use \t to specify a tab delimiter.

|Note   When a delimiter is inferred from the formatting of the file, consecutive whitespaces are treated as a single delimiter. By contrast, if a |

|delimiter is specified by the delimiter input, any repeated delimiter character is treated as a separate delimiter. |

M = dlmread(filename, delimiter, R, C) reads numeric data from the ASCII-delimited file filename, using the specified delimiter. The values R and C specify the row and column where the upper left corner of the data lies in the file. R and C are zero based, so that R=0, C=0 specifies the first value in the file, which is the upper left corner.

|Note   dlmread reads numeric data only. The file being read may contain nonnumeric data, but this nonnumeric data cannot be within the range being |

|imported. |

M = dlmread(filename, delimiter, range) reads the range specified by range = [R1 C1 R2 C2] where (R1,C1) is the upper left corner of the data to be read and (R2,C2) is the lower right corner. You can also specify the range using spreadsheet notation, as in range = 'A1..B7'.

Remarks

If you want to specify an R, C, or range input, but not a delimiter, set the delimiter argument to the empty string, (two consecutive single quotes with no spaces in between, ''). For example,

M = dlmread('myfile.dat', '', 5, 2)

Using this syntax enables you to specify the starting row and column or range to read while having dlmread treat repeated whitespaces as a single delimiter.

dlmread fills empty delimited fields with zero. Data files having lines that end with a nonspace delimiter, such as a semicolon, produce a result that has an additional last column of zeros.

dlmread imports any complex number as a whole into a complex numeric field, converting the real and imaginary parts to the specified numeric type. Valid forms for a complex number are

|Form |Example |

|±±i|j |5.7-3.1i |

|±i|j |-7j |

Embedded white-space in a complex number is invalid and is regarded as a field delimiter.

Examples

Example 1

Export the 5-by-8 matrix M to a file, and read it with dlmread, first with no arguments other than the filename:

rand('state', 0); M = rand(5,8); M = floor(M * 100);

dlmwrite('myfile.txt', M, 'delimiter', '\t')

dlmread('myfile.txt')

ans =

95 76 61 40 5 20 1 41

23 45 79 93 35 19 74 84

60 1 92 91 81 60 44 52

48 82 73 41 0 27 93 20

89 44 17 89 13 19 46 67

Now read a portion of the matrix by specifying the row and column of the upper left corner:

dlmread('myfile.txt', '\t', 2, 3)

ans =

91 81 60 44 52

41 0 27 93 20

89 13 19 46 67

This time, read a different part of the matrix using a range specifier:

dlmread('myfile.txt', '\t', 'C1..G4')

ans =

61 40 5 20 1

79 93 35 19 74

92 91 81 60 44

73 41 0 27 93

Example 2

Export matrix M to a file, and then append an additional matrix to the file that is offset one row below the first:

M = magic(3);

dlmwrite('myfile.txt', [M*5 M/5], ' ')

dlmwrite('myfile.txt', rand(3), '-append', ...

'roffset', 1, 'delimiter', ' ')

type myfile.txt

80 10 15 65 3.2 0.4 0.6 2.6

25 55 50 40 1 2.2 2 1.6

45 35 30 60 1.8 1.4 1.2 2.4

20 70 75 5 0.8 2.8 3 0.2

0.99008 0.49831 0.32004

0.78886 0.21396 0.9601

0.43866 0.64349 0.72663

When dlmread imports these two matrices from the file, it pads the smaller matrix with zeros:

dlmread('myfile.txt')

40.0000 5.0000 30.0000 1.6000 0.2000 1.2000

15.0000 25.0000 35.0000 0.6000 1.0000 1.4000

20.0000 45.0000 10.0000 0.8000 1.8000 0.4000

0.6038 0.0153 0.9318 0 0 0

0.2722 0.7468 0.4660 0 0 0

0.1988 0.4451 0.4187 0 0 0

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download