Importing and Exporting Data in MATLAB
Importing and exporting data are fundamental skills in MATLAB, especially when dealing
with real-world datasets for analysis and modeling. MATLAB provides a variety of functions
and tools to handle different data formats, allowing you to bring data into MATLAB for
processing and export results for use in other applications. This lesson will cover the most
common methods for importing and exporting data, including text files, spreadsheets, and
binary files. Understanding these techniques is crucial for effective data analysis and
statistical modeling in MATLAB.
Importing Data into MATLAB
MATLAB supports various file formats for importing data. The choice of method depends on
the file type and structure.
Importing Text Files
Text files are a common format for storing data. MATLAB provides several functions to read
data from text files.
readtable Function
The readtable function is a versatile tool for importing data from delimited text files, such
as CSV (Comma Separated Values) or TSV (Tab Separated Values) files. It automatically
detects the delimiter and data types, creating a table variable in MATLAB.
% Example: Importing data from a CSV file
filename = 'data.csv';
data = readtable(filename);
disp(data);
In this example, readtable reads the data from data.csv and stores it in a table
variable named data. The table variable provides a convenient way to access and
manipulate the data.
Example: Suppose you have a CSV file named temperature_data.csv with the
following content:
Date,Time,Temperature
2023-11-05,00:00,20.5
2023-11-05,01:00,20.2
2023-11-05,02:00,19.8
Using readtable:
temperatureData = readtable('temperature_data.csv');
disp(temperatureData);
MATLAB will create a table named temperatureData with columns 'Date', 'Time', and
'Temperature'.
Advanced Example: Handling missing data and specifying data types.
Suppose your CSV file has missing values represented by NaN and you want to specify the
data type for the 'Temperature' column:
Date,Time,Temperature
2023-11-05,00:00,20.5
2023-11-05,01:00,NaN
2023-11-05,02:00,19.8
opts = detectImportOptions('temperature_data.csv'); % Detect import options
opts = setvartype(opts, 'Temperature', 'double'); % Specify data type for
'Temperature'
opts.MissingRule = 'fill'; % Handle missing values by filling with NaN
temperatureData = readtable('temperature_data.csv', opts);
disp(temperatureData);
This code snippet first detects the import options, then sets the variable type for the
'Temperature' column to 'double', and specifies that missing values should be filled with NaN.
textscan Function
The textscan function provides more control over how data is read from a text file. It
requires specifying the format of the data using format specifiers.
% Example: Importing data using textscan
filename = 'data.txt';
fileID = fopen(filename, 'r'); % Open the file for reading
data = textscan(fileID, '%f %s %d'); % Read floating-point, string, and
integer data
fclose(fileID); % Close the file
disp(data);
In this example, textscan reads data from data.txt according to the specified format
'%f %s %d', which corresponds to a floating-point number, a string, and an integer. The
data is stored in a cell array named data.
Example: Reading data from a file with mixed data types.
Suppose you have a text file named student_data.txt with the following content:
101 John 22
102 Alice 21
103 Bob 23
Using textscan:
fileID = fopen('student_data.txt', 'r');
studentData = textscan(fileID, '%d %s %d');
fclose(fileID);
disp(studentData);
MATLAB will create a cell array named studentData containing the student IDs, names,
and ages.
Advanced Example: Skipping header lines and handling different delimiters.
Suppose your text file has a header line and uses a tab delimiter:
StudentID\tName\tAge
101\tJohn\t22
102\tAlice\t21
103\tBob\t23
fileID = fopen('student_data.txt', 'r');
header = fgetl(fileID); % Read and discard the header line
studentData = textscan(fileID, '%d%s%d', 'Delimiter', '\t');
fclose(fileID);
disp(studentData);
This code snippet first reads and discards the header line using fgetl, then reads the data
using textscan with the tab delimiter specified.
dlmread Function (Less Common, but still relevant)
The dlmread function is a simpler way to read numeric data from a delimited text file.
However, it is less flexible than readtable and textscan.
% Example: Importing numeric data using dlmread
filename = 'numeric_data.txt';
data = dlmread(filename, ','); % Read data with comma as delimiter
disp(data);
In this example, dlmread reads numeric data from numeric_data.txt, using a
comma as the delimiter, and stores it in a numeric array named data.
Example: Reading a matrix of numbers from a comma-separated file.
Suppose you have a text file named matrix_data.txt with the following content:
1,2,3
4,5,6
7,8,9
Using dlmread:
matrixData = dlmread('matrix_data.txt', ',');
disp(matrixData);
MATLAB will create a matrix named matrixData containing the numeric values.
Advanced Example: Specifying the range of data to read.
Suppose you only want to read the first two rows and the first two columns:
matrixData = dlmread('matrix_data.txt', ',', [0 0 1 1]); % [row_start
col_start row_end col_end]
disp(matrixData);
This code snippet reads only the top-left 2x2 submatrix from the file.
Importing Spreadsheet Files
MATLAB can import data from spreadsheet files, such as Excel files (.xls or .xlsx).
readtable Function (for Spreadsheets)
The readtable function can also be used to import data from spreadsheet files. It
automatically detects the data types and creates a table variable.
% Example: Importing data from an Excel file
filename = 'data.xlsx';
data = readtable(filename);
disp(data);
In this example, readtable reads the data from data.xlsx and stores it in a table
variable named data.
Example: Reading data from a specific sheet in an Excel file.
Suppose you have an Excel file named sales_data.xlsx with multiple sheets, and you
want to read data from the sheet named 'Sheet2':
salesData = readtable('sales_data.xlsx', 'Sheet', 'Sheet2');
disp(salesData);
MATLAB will create a table named salesData containing the data from 'Sheet2'.
Advanced Example: Specifying a range of cells to read.
Suppose you only want to read data from cells A1 to C10 in the Excel sheet:
salesData = readtable('sales_data.xlsx', 'Sheet', 'Sheet2', 'Range',
'A1:C10');
disp(salesData);
This code snippet reads only the specified range of cells from the Excel sheet.
xlsread Function (Legacy, but still used)
The xlsread function is an older function for reading data from Excel files. While still
functional, readtable is generally preferred for its flexibility and automatic data type
detection.
% Example: Importing data using xlsread
filename = 'data.xls';
[num, txt, raw] = xlsread(filename);
disp(num); % Numeric data
disp(txt); % Text data
disp(raw); % Raw data
In this example, xlsread reads data from data.xls and returns numeric data in num,
text data in txt, and raw data (both numeric and text) in raw.
Example: Reading numeric data from an Excel file.
[num, txt, raw] = xlsread('sales_data.xls');
disp(num);
MATLAB will display the numeric data from the Excel file.
Advanced Example: Reading data from a specific sheet and range.
[num, txt, raw] = xlsread('sales_data.xls', 'Sheet2', 'A1:C10');
disp(num);
This code snippet reads numeric data from 'Sheet2' in the range A1:C10.
Importing Binary Files
Binary files store data in a non-human-readable format. MATLAB provides functions to read
data from binary files, such as .mat files.
load Function
The load function is used to load variables from a .mat file into the MATLAB workspace.
% Example: Loading data from a .mat file
filename = 'data.mat';
load(filename); % Loads variables from data.mat into the workspace
disp(whos); % Display variables in the workspace
In this example, load reads the variables stored in data.mat and makes them available
in the MATLAB workspace.
Example: Loading specific variables from a .mat file.
Suppose your data.mat file contains variables x, y, and z, but you only want to load x
and y:
load('data.mat', 'x', 'y');
disp(whos);
MATLAB will load only the variables x and y into the workspace.
Advanced Example: Loading data into a structure.
data = load('data.mat'); % Load all variables into a structure
disp(data.x); % Access variable x
This code snippet loads all variables into a structure named data, and you can access
individual variables using dot notation.
Exporting Data from MATLAB
MATLAB provides functions to export data to various file formats, allowing you to share your
results with other applications or users.
Exporting to Text Files
writetable Function
The writetable function is used to export table variables to delimited text files, such as
CSV files.
% Example: Exporting a table to a CSV file
filename = 'output.csv';
writetable(data, filename);
In this example, writetable writes the data from the table variable data to a CSV file
named output.csv.
Example: Exporting a table with custom delimiter and quote characters.
writetable(temperatureData, 'output.txt', 'Delimiter', '\t', 'QuoteStrings',
true);
This code snippet exports the temperatureData table to a tab-separated file named
output.txt, and encloses strings in quotes.
Advanced Example: Excluding variable names from the output.
writetable(temperatureData, 'output.txt', 'WriteVariableNames', false);
This code snippet exports the temperatureData table without including the variable
names in the output file.
fprintf Function
The fprintf function provides more control over how data is written to a text file. It
requires specifying the format of the data using format specifiers.
% Example: Exporting data using fprintf
filename = 'output.txt';
fileID = fopen(filename, 'w'); % Open the file for writing
fprintf(fileID, '%f %s %d\n', data); % Write floating-point, string, and
integer data
fclose(fileID); % Close the file
In this example, fprintf writes data to output.txt according to the specified format
'%f %s %d\n', which corresponds to a floating-point number, a string, and an integer,
followed by a newline character.
Example: Writing data to a file with specific formatting.
fileID = fopen('student_data.txt', 'w');
for i = 1:length(studentData{1})
fprintf(fileID, '%d\t%s\t%d\n', studentData{1}(i), studentData{2}{i},
studentData{3}(i));
end
fclose(fileID);
This code snippet writes student data to a tab-separated file, iterating through the data and
formatting each line.
Advanced Example: Writing formatted output with headers.
fileID = fopen('student_data.txt', 'w');
fprintf(fileID, 'StudentID\tName\tAge\n'); % Write header
for i = 1:length(studentData{1})
fprintf(fileID, '%d\t%s\t%d\n', studentData{1}(i), studentData{2}{i},
studentData{3}(i));
end
fclose(fileID);
This code snippet writes a header line to the file before writing the data.
dlmwrite Function (Less Common, but still relevant)
The dlmwrite function is a simpler way to write numeric data to a delimited text file.
However, it is less flexible than writetable and fprintf.
% Example: Exporting numeric data using dlmwrite
filename = 'output.txt';
dlmwrite(filename, data, ','); % Write data with comma as delimiter
In this example, dlmwrite writes the numeric data from the array data to output.txt,
using a comma as the delimiter.
Example: Writing a matrix to a comma-separated file.
dlmwrite('matrix_data.txt', matrixData, ',');
This code snippet writes the matrixData matrix to a comma-separated file.
Advanced Example: Appending data to an existing file.
dlmwrite('matrix_data.txt', matrixData, ',', '-append');
This code snippet appends the matrixData matrix to the existing file.
Exporting to Spreadsheet Files
writetable Function (for Spreadsheets)
The writetable function can also be used to export table variables to spreadsheet files,
such as Excel files.
% Example: Exporting a table to an Excel file
filename = 'output.xlsx';
writetable(data, filename);
In this example, writetable writes the data from the table variable data to an Excel file
named output.xlsx.
Example: Writing data to a specific sheet in an Excel file.
writetable(salesData, 'output.xlsx', 'Sheet', 'Sheet2');
This code snippet writes the salesData table to 'Sheet2' in the Excel file.
Advanced Example: Writing data to a specific range of cells.
writetable(salesData, 'output.xlsx', 'Sheet', 'Sheet2', 'Range', 'A1:C10');
This code snippet writes the salesData table to the range A1:C10 in 'Sheet2'.
xlswrite Function (Legacy, but still used)
The xlswrite function is an older function for writing data to Excel files. While still
functional, writetable is generally preferred for its flexibility and automatic data type
handling.
% Example: Exporting data using xlswrite
filename = 'output.xls';
xlswrite(filename, data);
In this example, xlswrite writes the data from the array data to an Excel file named
output.xls.
Example: Writing data to a specific sheet.
xlswrite('sales_data.xls', salesData, 'Sheet2');
This code snippet writes the salesData matrix to 'Sheet2' in the Excel file.
Advanced Example: Writing data to a specific range.
xlswrite('sales_data.xls', salesData, 'Sheet2', 'A1:C10');
This code snippet writes the salesData matrix to the range A1:C10 in 'Sheet2'.
Exporting to Binary Files
save Function
The save function is used to save variables from the MATLAB workspace to a .mat file.
% Example: Saving data to a .mat file
filename = 'output.mat';
save(filename, 'data'); % Saves the variable data to output.mat
In this example, save writes the variable data to a .mat file named output.mat.
Example: Saving multiple variables to a .mat file.
save('output.mat', 'x', 'y', 'z');
This code snippet saves the variables x, y, and z to the .mat file.
Advanced Example: Saving all variables in the workspace.
save('output.mat'); % Saves all variables in the workspace
This code snippet saves all variables currently in the workspace to the .mat file.
Practice Activities
1. Importing and Analyzing Temperature Data:
● Download a CSV file containing daily temperature data (Date, High, Low).
● Use readtable to import the data into MATLAB.
● Calculate the average daily temperature (average of High and Low).
● Export the results to a new CSV file using writetable.
2. Processing Student Records:
● Create a text file with student records (StudentID, Name, Major, GPA).
● Use textscan to import the data.
● Filter the records to find students with a GPA above 3.5.
● Export the filtered records to a new text file using fprintf.
3. Working with Excel Sales Data:
● Create an Excel file with sales data (Product, Quantity, Price, Date).
● Use readtable to import the data.
● Calculate the total sales for each product.
● Export the results to a new sheet in the same Excel file using writetable.
4. Saving and Loading Simulation Results:
● Run a simulation in MATLAB that generates several variables (e.g., time,
position, velocity).
● Use save to save these variables to a .mat file.
● Clear the workspace and then use load to load the variables back into
MATLAB.
● Plot the simulation results.