Academic Block

File Input/Output Operations in MATLAB Get Certified

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);

Expected output:

Data from the file:
   (the numbers stored in map_data.txt, displayed as a column)

If the file cannot be opened, MATLAB stops with the error: File cannot be opened

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);

Expected output:

Parsed Data:
    {3x1 int32}    {3x1 cell}    {3x1 double}

(shown here for a file with 3 lines such as "1,apple,2.5". The number of rows depends on your file.)

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);

Expected output:

Numeric data from CSV:
   (the numbers in data.csv, as a matrix)

Tabular data from CSV:
   (the same data as a table, with its column headings)

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);

Expected output:

Excel Data:
   (the contents of the first sheet of data.xlsx, as a table)

Numeric Data:
   (the numeric values of the sheet, as a matrix)

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');

Expected output:

Data written to output.txt

Contents of output.txt:
Matrix A:
1 2
3 4

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');

Expected output:

Numeric data saved to output.csv

Contents of output.csv:
1,2,3
4,5,6
7,8,9

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);

Expected output:

Variables saved to output.mat
Loaded Variable A:
    10    20
    30    40

Loaded Variable B:
    {'Hello'}    {'World'}

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)]);

Expected output:

Mean value: 13.3333

(shown for an example log.txt containing the three lines
10:00,12.5
10:01,14.5
10:02,13.0
The result depends on the values in your own file.)

Example 2: Writing a Table to CSV

Create a table with three columns (a number, its square and its cube) and save it as a CSV file:

% 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');

Expected output:

Table saved to table_output.csv

First lines of table_output.csv:
Number,Square,Cube
1,1,1
2,4,8
3,9,27
...
10,100,1000

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.');

Expected output:

Large data saved in chunks.

First and last lines of large_output.txt:
1 1 1
2 4 8
3 9 27
...
1000 1000000 1000000000

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.