How to Use textscan in MATLAB for Reading Text Data
Use
textscan in MATLAB to read formatted data from text files or strings by specifying a file identifier and a format string. It returns data in cell arrays, allowing easy extraction of different data types from mixed content.Syntax
The basic syntax of textscan is:
C = textscan(fileID, formatSpec)reads data from an open file.C = textscan(fileID, formatSpec, N)reads N times according to the format.C = textscan(fileID, formatSpec, Name, Value)uses additional options like delimiters.
Here, fileID is the file handle from fopen, formatSpec defines the data types to read, and C is a cell array with the parsed data.
matlab
fileID = fopen('data.txt','r'); data = textscan(fileID, '%s %d %f'); fclose(fileID);
Example
This example reads a text file with three columns: a string, an integer, and a floating-point number. It shows how textscan parses mixed data types into separate cells.
matlab
fileID = fopen('example.txt','w'); fprintf(fileID, 'John 25 72.5\nAnna 30 65.2\nMike 22 80.1\n'); fclose(fileID); fileID = fopen('example.txt','r'); data = textscan(fileID, '%s %d %f'); fclose(fileID); names = data{1}; ages = data{2}; weights = data{3}; disp(names); disp(ages); disp(weights);
Output
'John'
'Anna'
'Mike'
25
30
22
72.5000
65.2000
80.1000
Common Pitfalls
Common mistakes when using textscan include:
- Not opening the file before reading or forgetting to close it after.
- Using incorrect format specifiers that don't match the data.
- Ignoring delimiters when data is separated by commas or tabs.
- Assuming output is a matrix instead of a cell array.
Always check the file format and specify delimiters if needed.
matlab
fileID = fopen('data.csv','r'); % Wrong: missing delimiter for CSV % data = textscan(fileID, '%s %d %f'); % Right: specify delimiter data = textscan(fileID, '%s %d %f', 'Delimiter', ','); fclose(fileID);
Quick Reference
Tips for using textscan effectively:
- Use
fopenandfcloseto manage files. - Match
formatSpecto your data types (e.g.,%sfor strings,%dfor integers,%ffor floats). - Specify delimiters with
'Delimiter'option if data is not space-separated. - Use
'HeaderLines'to skip unwanted lines. - Remember output is a cell array; access data with curly braces.
Key Takeaways
Use textscan with a file ID and format string to read mixed data types from text files.
Always open files with fopen and close them with fclose to avoid errors.
Specify delimiters and header lines to match your file's structure.
Output from textscan is a cell array; access each column with curly braces.
Check your format specifiers carefully to match the data types in your file.