| MATLAB® | ![]() |
| On this page… |
|---|
Reading Files with Different Formats |
For more information and examples on importing and exporting data, see Technical Note 1602:
http://www.mathworks.com/support/tech-notes/1600/1602.html
For a good overview of MATLAB® file I/O functions, use the online "Functions — Categorical List" reference. In the Help browser Contents, select MATLAB > Functions — Categorical List, and then click File I/O.
The most commonly used, high-level, file I/O functions in MATLAB are save and load. For help on these, type doc save or doc load.
Functions for I/O to text files with delimited values are textread, dlmread, dlmwrite. Functions for I/O to text files with comma-separated values are csvread, csvwrite.
For more information: See Text Files in the MATLAB "Functions — Categorical List" reference documentation.
Type doc fileformats to see a list of file formats that MATLAB can read, along with the associated MATLAB functions.
A quick method of importing text or binary data from a file (e.g., Excel files) is to use the MATLAB Import Wizard. Open the Import Wizard with the command, uiimport filename or by selecting File > Import Data at the Command Window.
Specify or browse for the file containing the data you want to import and you will see a preview of what the file contains. Select the data you want and click Finish.
For more information: See Using the Import Wizard in the MATLAB Programming Fundamentals documentation.
To load data that is in mixed formats, use textread instead of load. The textread function lets you specify the format of each piece of data.
If the first line of file mydata.dat is
Sally 12.34 45
Read the first line of the file as a free format file using the % format:
[names, x, y] = textread('mydata.dat', '%s %f %d', 1)
returns
names =
'Sally'
x =
12.34000000000000
y =
45
Attempting to read data from a file that was generated on a different platform may result in an error because the binary formats of the platforms may differ. Using the fopen function, you can specify a machine format when you open the file to avoid these errors.
A common technique used to read an ASCII data file into a cell array is
[a,b,c,d] = textread('data.txt', '%s %s %s %s');
mydata = cellstr([a b c d]);
For more information: See the textread and cellstr function reference pages.
Your program can accept interactive input from users during execution. Use the input function to prompt the user for input, and then read in a response. When executed, input causes the program to display your prompt, pause while a response is entered, and then resume when the Enter key is pressed.
![]() | Files and Filenames | Starting MATLAB® | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |