MATLAB - Data Import
Modern Data Import in MATLAB
Section titled “Modern Data Import in MATLAB”Importing data is the first step in most data analysis workflows. MATLAB offers a powerful and flexible set of tools to load data from various file formats. While older methods focused on general-purpose functions, modern MATLAB encourages using specialized, high-performance functions tailored to specific data types, primarily readtable for tabular data and readmatrix for numeric arrays.
The Modern Approach: High-Level I/O Functions
Section titled “The Modern Approach: High-Level I/O Functions”For most common tasks, you should prefer MATLAB’s high-level import functions. They are optimized for performance, automatically handle many common formatting issues, and return data in convenient, modern data structures like tables and matrices.
| Function | Best For |
|---|---|
readtable | The recommended function for tabular data (e.g., CSV, TXT, XLSX). It can infer data types, handle missing values, and reads data into a table, which preserves column headers and mixed data types. |
readmatrix | Ideal for files containing purely numeric, matrix-like data. It’s faster than readtable for these cases and returns a standard numeric matrix. |
readcell | Use when you have mixed data but need to preserve the original cell structure of a file, without the structured organization of a table. |
importdata | A versatile, general-purpose function that can handle many file types, including images and text files. It’s a good fallback but can sometimes produce less predictable output formats compared to the specialized functions. |
webread | Reads content from RESTful web services and web pages. Essential for integrating data from online APIs. |
Example 1: Importing Tabular Data with readtable
Section titled “Example 1: Importing Tabular Data with readtable”Let’s import a text file with column headers. This is the most common data import task. Consider a file named weeklydata.csv with the following content:
Day,Temperature,HumidityMonday,22.5,55Tuesday,24.1,52Wednesday,23.8,58Thursday,25.0,60Friday,21.9,49The modern approach is to use readtable. It automatically detects the delimiter (comma), identifies the header row, and parses the numeric data.
% Best Practice: Use fullfile to create platform-independent paths% Ensure 'weeklydata.csv' is in your current MATLAB path.filename = 'weeklydata.csv';
% Use a try-catch block for robust error handlingtry % readtable automatically detects headers and delimiters dataTable = readtable(filename);
% Display the imported table disp('Successfully imported data as a table:'); disp(dataTable);
% Accessing data is intuitive fprintf('\nMean Temperature: %.2f\n', mean(dataTable.Temperature));
catch ME % Provide a user-friendly error message fprintf('Error importing file: %s\n', ME.message);endWhen you run the file, readtable returns a table variable, which is the modern standard for handling mixed-type columnar data in MATLAB. The output will be:
Successfully imported data as a table: Day Temperature Humidity ___________ ___________ ________
"Monday" 22.5 55 "Tuesday" 24.1 52 "Wednesday" 23.8 58 "Thursday" 25 60 "Friday" 21.9 49
Mean Temperature: 23.46Example 2: Importing an Image with importdata
Section titled “Example 2: Importing an Image with importdata”importdata is still excellent for non-tabular data like images. For image-specific tasks, functions from the Image Processing Toolbox™ like imread are even better, but importdata is great for quick loading.
% Ensure an image file (e.g., 'peppers.png', a standard MATLAB demo image) is available.filename = 'peppers.png';
try imageData = importdata(filename);
% The `image` function is suitable for quick display. % For more control, use `imshow`. figure; % Create a new figure window imshow(imageData); title(['Image: ', filename], 'Interpreter', 'none');
catch ME fprintf('Could not load or display image. Error: %s\n', ME.message);endLow-Level File I/O: For Maximum Control
Section titled “Low-Level File I/O: For Maximum Control”Low-level file I/O functions like fopen, fscanf, and fclose grant you complete control over the data reading process. You should use them only when high-level functions fail, for example, with non-standard file formats, binary files with complex structures, or when memory usage must be minimized by reading a file line-by-line.
Best Practice: Always use a try-catch block with a finally clause to ensure fclose is called, even if an error occurs during reading. This prevents file handles from being left open.
The main low-level functions are:
| Function | Description |
|---|---|
| fopen | Open file, or obtain information about open files. Returns a file identifier. |
| fclose | Close one or all open files. Crucial for preventing resource leaks. |
| fgetl | Read a single line from a file as text, discarding the newline character. |
| textscan | Reads data from a text file or string into a cell array. More powerful and flexible than fscanf. |
| fread | Read data from a binary file into a matrix. |
| fwrite | Write data to a binary file. |
| fprintf | Write formatted data to a text file. |
Example 3: Low-Level I/O with textscan
Section titled “Example 3: Low-Level I/O with textscan”Let’s revisit the rainfall data from the original tutorial (myfile.txt). Manually parsing this with fscanf is complex and error-prone. A more robust modern approach uses fgetl to skip headers and textscan to read the structured data.
/* myfile.txt content */Rainfall DataMonths: June, July, August
M = 312:00:00June-201217.21 28.52 39.78 16.55 23.6719.15 0.35 17.57 NaN 12.01...Here’s a more modern and safer way to parse this file.
filename = 'myfile.txt';fid = -1; % Initialize file ID to an invalid value
try fid = fopen(filename, 'r'); if fid == -1 error('CannotOpenFile', 'Could not open the file: %s', filename); end
% Skip the first 3 header lines for i = 1:3, fgetl(fid); end
% Read the number of months headerLine = fgetl(fid); numMonths = sscanf(headerLine, 'M = %d');
% Pre-allocate a struct array for efficiency myData(numMonths) = struct('time', [], 'month', [], 'raindata', []);
% Define the format for the numeric data block (5 columns of floats) formatSpec = '%f %f %f %f %f';
for n = 1:numMonths fgetl(fid); % Skip blank line myData(n).time = fgetl(fid); myData(n).month = fgetl(fid); % Use textscan to read the next 7 lines of numeric data dataBlock = textscan(fid, formatSpec, 7, 'CollectOutput', true); myData(n).raindata = dataBlock{1}; end
disp('Data successfully parsed using low-level I/O.'); disp(myData);
catch ME fprintf(2, 'An error occurred: %s\n', ME.message);
finally % This block executes whether an error occurred or not if fid ~= -1 fclose(fid); disp('File closed.'); endendCommon Errors & Debugging Tips
Section titled “Common Errors & Debugging Tips”- Error: File not found. Check that the file is in the current MATLAB folder or on the MATLAB path. Use
pwdto see the current folder andexist(filename, 'file')to check if the file is visible to MATLAB. - Error: Incorrect data types or columns. If
readtablemisinterprets your data, use its options to specify variable names, types, and ranges. Use'Delimiter'and'HeaderLines'name-value pairs. - Performance: Slow import for large files. For very large text files,
readmatrixis often faster thanreadtable. For files that don’t fit in memory, usedatastoreto work with the data in chunks. - Low-Level I/O: Unclosed files. Forgetting
fclose(fid)can lock files and consume system resources. Always use atry-catch-finallystructure to guarantee files are closed.