Academic Block

Logo of Academicblock.net

File Input/Output Operations in MATLAB

File Input/Output (I/O) operations are essential for managing external data in MATLAB. These include reading from and writing to text files, CSV files, Excel files, and MAT-files. Below, we explore these operations with detailed examples and explanations.

Reading from Files

MATLAB supports various methods to read data, including text files, CSV files, and Excel files. Examples are provided for each type:

Reading Text Files

Use fopen to open a file, fscanf or fgets to read data, and fclose to close the file:

% Open a text file for reading
fid = fopen('C:/Users/JohnWick/files/map_data.txt', 'r');
if fid == -1
error('File cannot be opened');
end
% Read numeric data from the file
data = fscanf(fid, '%f'); % Reads all numeric values
disp('Data from the file:');
disp(data);
% Close the file
fclose(fid);

If the text file contains mixed data types (e.g., numbers and text), consider using textscan:

% Open a text file
fid = fopen('example_mixed.txt', 'r');
% Read data line by line with specific format
data = textscan(fid, '%d %s %f', 'Delimiter', ',');
disp('Parsed Data:');
disp(data);
fclose(fid);

Reading CSV Files

CSV files can be read using readmatrix for numeric data or readtable for tabular data:

% Read data from a CSV file
data = readmatrix('data.csv'); % For numeric data
disp('Numeric data from CSV:');
disp(data);
% For tabular data:
tableData = readtable('data.csv');
disp('Tabular data from CSV:');
disp(tableData);

Reading Excel Files

MATLAB can directly read Excel files using readtable, readmatrix, or xlsread:

% Read an entire Excel sheet into a table
data = readtable('data.xlsx');
disp('Excel Data:');
disp(data);
% Read only numeric data
numericData = readmatrix('data.xlsx');
disp('Numeric Data:');
disp(numericData);

Writing to Files

Writing data to files is straightforward in MATLAB. Here are examples for text, CSV, and MAT-files:

Writing to Text Files

Text files can be written using fprintf:

% Open a text file for writing
fid = fopen('output.txt', 'w');
% Write formatted data to the file
fprintf(fid, 'Matrix A:\n');
A = [1, 2; 3, 4];
fprintf(fid, '%d %d\n', A'); % Transpose to write row-wise
% Close the file
fclose(fid);
disp('Data written to output.txt');

Writing to CSV Files

To save numeric data to a CSV file, use writematrix:

% Save numeric data to a CSV file
data = [1, 2, 3; 4, 5, 6; 7, 8, 9];
writematrix(data, 'output.csv');
disp('Numeric data saved to output.csv');

Writing to MAT-Files

MAT-files are MATLAB’s native format for storing variables:

% Save variables to a MAT-file
A = [10, 20; 30, 40];
B = {'Hello', 'World'};
save('output.mat', 'A', 'B');
disp('Variables saved to output.mat');
% Load variables back
load('output.mat');
disp('Loaded Variable A:');
disp(A);
disp('Loaded Variable B:');
disp(B);

Advanced File I/O Examples

Here are some practical problems and their solutions:

Example 1: Processing a Log File

Suppose you have a log file with timestamps and data values. Extract the data values and compute the mean:

% Open and process a log file
fid = fopen('log.txt', 'r');
data = [];
while ~feof(fid)
line = fgets(fid);
parts = split(line, ','); % Split line by comma
value = str2double(parts{2}); % Extract the second column
data = [data; value]; % Append to data array
end
fclose(fid);
meanValue = mean(data);
disp(['Mean value: ', num2str(meanValue)]);

Example 2: Writing a Table to CSV

% Create and write a table to CSV
T = table((1:10)', (1:10)'.^2, (1:10)'.^3, ...
'VariableNames', {'Number', 'Square', 'Cube'});
writetable(T, 'table_output.csv');
disp('Table saved to table_output.csv');

Example 3: Saving Large Data in Chunks

For very large datasets, it might be beneficial to save data in chunks:

% Save a large matrix in chunks
fid = fopen('large_output.txt', 'w');
for i = 1:1000 % Write 1000 lines
fprintf(fid, '%d %d %d\n', i, i^2, i^3);
end
fclose(fid);
disp('Large data saved in chunks.');

Useful MATLAB Functions for File I/O

Function
Explanation
fopen
Opens a file for reading or writing.
fclose
Closes an open file.
fprintf
Writes formatted data to a text file.
readmatrix
Reads numeric data from a file.
writematrix
Writes numeric data to a file.
readtable
Reads tabular data from files.
save
Saves variables to a MAT-file.
load
Loads variables from a MAT-file.

Practice Questions

Test Yourself

1. Read a CSV file and calculate the sum of each column.

2. Write a matrix to a text file, then read it back and verify the contents.

3. Create a MATLAB script to log real-time data to a text file.