We use readtable and textscan to get data from text files into MATLAB so we can work with it easily.
Reading text files (readtable, textscan) in 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.
T = readtable('data.csv')fileID = fopen('data.txt','r'); data = textscan(fileID, '%s %f %d'); fclose(fileID);
T = readtable('data.txt', 'Delimiter', '\t')
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.
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);
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.
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.