How to Read File in MATLAB: Syntax and Examples
In MATLAB, you can read files using functions like
fopen to open the file, fread or fscanf to read data, and fclose to close the file. For structured data like tables, use readtable for easy reading of CSV or text files.Syntax
Here are common ways to read files in MATLAB:
fid = fopen(filename, permission): Opens a file and returns a file ID.data = fread(fid, size, precision): Reads binary data from the file.data = fscanf(fid, formatSpec): Reads formatted data as text.fclose(fid): Closes the opened file.tableData = readtable(filename): Reads tabular data from a file into a table.
matlab
fid = fopen('data.txt', 'r'); data = fscanf(fid, '%f'); fclose(fid); tableData = readtable('data.csv');
Example
This example reads numbers from a text file named numbers.txt and prints them. It also shows how to read a CSV file into a table.
matlab
fid = fopen('numbers.txt', 'r'); if fid == -1 error('File cannot be opened'); end numbers = fscanf(fid, '%f'); fclose(fid); disp('Numbers read from file:'); disp(numbers); % Reading CSV file into a table filename = 'data.csv'; tableData = readtable(filename); disp('Table data:'); disp(tableData);
Output
Numbers read from file:
1
2
3
4
5
Table data:
Name Age Score
_____ ____ _____
'Amy' 25 88
'Bob' 30 92
'Cara' 22 95
Common Pitfalls
Common mistakes when reading files in MATLAB include:
- Not checking if
fopensuccessfully opened the file (it returns -1 if it fails). - Forgetting to close the file with
fclose, which can lock the file. - Using wrong format specifiers in
fscanfcausing incorrect data reading. - Trying to read structured data with
fscanfinstead ofreadtablefor CSV or tabular files.
matlab
%% Wrong way: Not checking fopen result fid = fopen('missing.txt', 'r'); if fid == -1 error('File not found or cannot be opened'); end % Proceed to read fclose(fid); %% Right way: Check fopen fid = fopen('missing.txt', 'r'); if fid == -1 error('File not found or cannot be opened'); end % Proceed to read fclose(fid);
Quick Reference
Summary tips for reading files in MATLAB:
- Use
fopen,fread,fscanf, andfclosefor low-level file reading. - Use
readtablefor CSV or structured text files. - Always check if the file opened successfully.
- Close files after reading to free resources.
Key Takeaways
Use fopen and fclose to open and close files safely in MATLAB.
Use fscanf or fread to read raw data, and readtable for structured tables.
Always check if fopen returns a valid file ID before reading.
Close files after reading to avoid locking issues.
Choose the right reading function based on file type and data format.