Quantcast

Documentation Center

  • Trial Software
  • Product Updates

Import Data from a Nonrectangular Text File

This example shows how to import data from a nonrectangular file using the textscan function. When using textscan, your data does not have to be in a regular pattern of columns and rows, but it must be in a repeated pattern.

Create a file named nonrect.dat that contains the following (copy and paste into a text editor):

begin
v1=12.67
v2=3.14
v3=6.778
end
begin
v1=21.78
v2=5.24
v3=9.838
end

Open the file to read using the fopen function.

fileID = fopen('nonrect.dat');

fopen returns a file identifier, fileID, that textscan calls to read from the file.

Describe the pattern of the file data using format specifiers and delimiter parameters. Typical format specifiers include '%s' for a string, '%d' for an integer, or '%f' for a floating-point number. To import nonrect.dat, use the format specifier '%*s' to tell textscan to skip the strings begin and end. Include the literals 'v1=', 'v2=', and 'v3=' as part of the format specifiers, so that textscan ignores those strings as well.

formatSpec = '%*s v1=%f v2=%f v3=%f %*s';

Import the data using textscan. Pass the file identifier and formatSpec as inputs. Since each data field is on a new line, the delimiter is a newline character ('\n'). To combine all the floating-point data into a single array, set the CollectOutput name-value pair argument to true.

C = textscan(fileID,formatSpec,...            
                'Delimiter', '\n', ...
                'CollectOutput', true)
C = 

    [2x3 double]

textscan returns the cell array, C.

Close the file.

fclose(fileID);

View the contents of C.

celldisp(C)
C{1} =
 
   12.6700    3.1400    6.7780
   21.7800    5.2400    9.8380

See Also

More About

Was this topic helpful?