0
0
MATLABdata~5 mins

Reading text files (readtable, textscan) in MATLAB

Choose your learning style9 modes available
Introduction

We use readtable and textscan to get data from text files into MATLAB so we can work with it easily.

You have a spreadsheet saved as a text file and want to analyze the data.
You want to read a file with mixed types of data like numbers and words.
You need to process large text files line by line or in parts.
You want to import data with custom separators or formats.
Syntax
MATLAB
T = readtable(filename)

fileID = fopen(filename,'r');
data = textscan(fileID, formatSpec);
fclose(fileID);

readtable automatically detects columns and types, making it easy for tables.

textscan gives more control for custom formats but needs you to open and close the file.

Examples
Reads a CSV file into a table automatically.
MATLAB
T = readtable('data.csv')
Reads a text file with three columns: string, float, and integer.
MATLAB
fileID = fopen('data.txt','r');
data = textscan(fileID, '%s %f %d');
fclose(fileID);
Reads a tab-delimited text file into a table.
MATLAB
T = readtable('data.txt', 'Delimiter', '\t')
Sample Program

This program creates a small text file with names, ages, and scores. It reads the file first with readtable to get a table, then with textscan to get a cell array of data.

MATLAB
filename = 'sample.txt';
% Create a sample text file
fid = fopen(filename, 'w');
fprintf(fid, 'Name Age Score\nAlice 30 85.5\nBob 25 90.0\n');
fclose(fid);

% Read the file using readtable
T = readtable(filename);

% Display the table
disp(T);

% Read the file using textscan
fileID = fopen(filename, 'r');
header = fgetl(fileID); % skip header line
formatSpec = '%s %d %f';
data = textscan(fileID, formatSpec);
fclose(fileID);

% Display data from textscan
disp(data);
OutputSuccess
Important Notes

Always close files opened with fopen using fclose to avoid errors.

readtable is simpler for common table-like files, but textscan is better for custom formats.

Use the format specifiers like %s for strings, %d for integers, and %f for floating-point numbers in textscan.

Summary

readtable quickly loads text files into tables with automatic formatting.

textscan reads text files with detailed control over data types and format.

Always remember to open files before reading and close them after.