Import Numeric Data from Text Files

Import Comma-Separated Data

This example shows how to import comma-separated numeric data from a text file, using the csvread function.

Create a sample file named ph.dat that contains the following comma-separated data:

85.5, 54.0, 74.7, 34.2
63.0, 75.6, 46.8, 80.1
85.5, 39.6, 2.7, 38.7
A = 0.9*gallery('integerdata',99,[3,4],1);
dlmwrite('ph.dat',A,',')

The sample file, ph.dat, resides in your current folder.

Read the entire file using csvread. The file name is the only required input argument to the csvread function.

M = csvread('ph.dat')
M =

   85.5000   54.0000   74.7000   34.2000
   63.0000   75.6000   46.8000   80.1000
   85.5000   39.6000    2.7000   38.7000

M is a 3-by-4 double array containing the data from the file.

Import only the rectangular portion of data starting from the first row and third column in the file. When using csvread, row and column indices are zero-based.

N = csvread('ph.dat',0,2)
N =

   74.7000   34.2000
   46.8000   80.1000
    2.7000   38.7000

Import Delimited Numeric Data

This example shows how to import numeric data delimited by any single character using the dlmread function.

Create a tab-delimited file named num.txt that contains the following data:

95    89    82    92
23    76    45    74
61    46    61    18
49     2    79    41
A = gallery('integerdata',99,[4,4],0);
dlmwrite('num.txt',A,'\t')

The sample file, num.txt, resides in your current folder.

Read the entire file. The file name is the only required input argument to the dlmread function. dlmread determines the delimiter from the formatting of the file.

M = dlmread('num.txt')
M =

    95    89    82    92
    23    76    45    74
    61    46    61    18
    49     2    79    41

M is a 4-by-4 double array containing the data from the file.

Read only the rectangular block of data beginning from the second row, third column, in the file. When using dlmread, row and column indices are zero-based. When you specify a specific range to read, you must also specify the delimiter. Use '\t' to indicate a tab delimiter.

N = dlmread('num.txt','\t',1,2)
N =

    45    74
    61    18
    79    41

dlmread returns a 3-by-2 double array.

Read only the first two columns. You can use spreadsheet notation to indicate the range, in this case, 'A1..B4'.

P = dlmread('num.txt','\t','A1..B4')
P =

    95    89
    23    76
    61    46
    49     2

See Also

|

Was this topic helpful?