Bird
Raised Fist0
MATLABdata~20 mins

Reading text files (readtable, textscan) in MATLAB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Reading Text Files
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of readtable with mixed data types
What is the output of the following MATLAB code snippet when reading a text file with mixed numeric and text columns?
MATLAB
fid = fopen('data.txt','w');
fprintf(fid, 'ID Age Name\n1 25 Alice\n2 30 Bob\n3 22 Carol');
fclose(fid);
T = readtable('data.txt');
disp(T);
AA table with variables: ID (double), Age (double), Name (string) and 3 rows showing the data
BA table with variables: ID (double), Age (double), Name (cell) and 3 rows showing the data
CError: File not found
DA numeric matrix with values [1 25; 2 30; 3 22]
Attempts:
2 left
💡 Hint
readtable automatically detects variable types and reads text columns as strings or categorical by default.
❓ Predict Output
intermediate
2:00remaining
Output of textscan with delimiter and format specifiers
What is the output of this MATLAB code reading a text file with textscan?
MATLAB
fid = fopen('data2.txt','w');
fprintf(fid, 'John,25,180.5\nJane,30,165.2\n');
fclose(fid);
fid = fopen('data2.txt','r');
C = textscan(fid, '%s %d %f', 'Delimiter', ',');
fclose(fid);
disp(C);
AA 1x3 cell array: {1x2 cell of strings, [25 30], [180.5 165.2]}
BA 1x3 cell array: {1x2 cell of strings, [25;30], [180.5;165.2]}
CA numeric matrix with values [25 180.5; 30 165.2]
DError: Format specifier mismatch
Attempts:
2 left
💡 Hint
textscan returns a cell array with each cell containing a column of data matching the format specifiers.
🔧 Debug
advanced
2:00remaining
Identify the error in textscan usage
What error does this MATLAB code produce when trying to read a file with textscan?
MATLAB
fid = fopen('data3.txt','w');
fprintf(fid, 'A 10\nB 20\n');
fclose(fid);
fid = fopen('data3.txt','r');
C = textscan(fid, '%s %d %f');
fclose(fid);
AError: Not enough input arguments for format specifiers
BError: File not found
CNo error, returns a cell array with 3 columns
DError: Invalid format specifier
Attempts:
2 left
💡 Hint
Check if the number of format specifiers matches the number of data columns in the file.
❓ Predict Output
advanced
2:00remaining
Result of readtable with missing data and options
What is the output of this MATLAB code reading a file with missing values using readtable?
MATLAB
fid = fopen('data4.txt','w');
fprintf(fid, 'Name,Score,Age\nAlice,90,25\nBob,,30\nCarol,85,\n');
fclose(fid);
opts = detectImportOptions('data4.txt');
opts = setvaropts(opts, 'Score', 'TreatAsMissing', '');
opts = setvaropts(opts, 'Age', 'TreatAsMissing', '');
T = readtable('data4.txt', opts);
disp(T);
ATable with zeros in place of missing numeric data
BTable with empty strings in Score and Age columns for missing data
CError: Missing data not handled
DTable with missing numeric values as NaN in Score and Age columns for Bob and Carol
Attempts:
2 left
💡 Hint
readtable with import options can treat empty fields as missing and convert them to NaN for numeric columns.
🧠 Conceptual
expert
2:00remaining
Choosing between readtable and textscan for large files
Which statement best explains when to prefer textscan over readtable for reading large text files in MATLAB?
Atextscan cannot handle mixed data types, so readtable is better for any file with text and numbers
Breadtable is always faster and better for large files because it automatically detects formats
Ctextscan is preferred when you need fine control over reading format and want to process data line-by-line efficiently
Dreadtable requires manual format specification, while textscan automatically detects data types
Attempts:
2 left
💡 Hint
Consider flexibility and performance when reading large files with complex formats.

Practice

(1/5)
1. What is the main advantage of using readtable in MATLAB to read text files?
easy
A. It reads files without opening them first.
B. It requires manual specification of each data type.
C. It only reads numeric data, ignoring text.
D. It automatically loads data into a table with proper formatting.

Solution

  1. Step 1: Understand readtable functionality

    readtable is designed to load text files directly into tables, automatically detecting and formatting columns.
  2. Step 2: Compare options

    It automatically loads data into a table with proper formatting. correctly describes this automatic loading and formatting. Other options describe incorrect behaviors.
  3. Final Answer:

    It automatically loads data into a table with proper formatting. -> Option D
  4. Quick Check:

    readtable = automatic table loading [OK]
Hint: Remember: readtable = easy table import [OK]
Common Mistakes:
  • Thinking readtable needs manual type input
  • Assuming readtable only reads numbers
  • Believing files don't need opening before reading
2. Which of the following is the correct syntax to open a text file named data.txt for reading in MATLAB?
easy
A. fileID = fopen('data.txt', 'r');
B. fileID = open('data.txt', 'r');
C. fileID = readfile('data.txt');
D. fileID = textscan('data.txt', 'r');

Solution

  1. Step 1: Recall file opening function

    In MATLAB, fopen is used to open files with a mode like 'r' for reading.
  2. Step 2: Check each option

    fileID = fopen('data.txt', 'r'); uses fopen correctly. fileID = open('data.txt', 'r'); uses a non-existent open function. fileID = readfile('data.txt'); uses readfile which is not a MATLAB function. fileID = textscan('data.txt', 'r'); misuses textscan which reads from an open file, not opens it.
  3. Final Answer:

    fileID = fopen('data.txt', 'r'); -> Option A
  4. Quick Check:

    Open file = fopen(filename, 'r') [OK]
Hint: Use fopen to open files before reading [OK]
Common Mistakes:
  • Using open instead of fopen
  • Trying to read file directly without fopen
  • Confusing textscan with fopen
3. Given the following MATLAB code snippet, what will be the output stored in data?
fileID = fopen('numbers.txt', 'r');
data = textscan(fileID, '%d %f');
fclose(fileID);
Assuming numbers.txt contains:
10 3.14
20 2.71
30 1.62
medium
A. A 1x2 cell array with first cell [10;20;30] and second cell [3.14;2.71;1.62]
B. A 3x2 numeric matrix with all numbers
C. A single numeric array combining all values
D. An error because textscan cannot read mixed data

Solution

  1. Step 1: Understand textscan output format

    textscan returns a cell array where each cell contains a column of data matching the format specifiers.
  2. Step 2: Analyze the format and file content

    Format '%d %f' reads an integer and a float per line. The file has 3 lines, so the first cell will be [10;20;30] and the second cell [3.14;2.71;1.62].
  3. Final Answer:

    A 1x2 cell array with first cell [10;20;30] and second cell [3.14;2.71;1.62] -> Option A
  4. Quick Check:

    textscan returns cell array columns [OK]
Hint: textscan returns cells, each for one format column [OK]
Common Mistakes:
  • Expecting a numeric matrix instead of cell array
  • Thinking textscan merges all data into one array
  • Assuming textscan cannot read mixed types
4. Consider this MATLAB code snippet:
fileID = fopen('data.txt', 'r');
data = textscan(fileID, '%s %d');
What is the main problem with this code?
medium
A. textscan cannot read strings and integers together.
B. The format specifier '%s %d' is invalid.
C. The file is not closed after reading.
D. fopen should be called with 'w' mode to read.

Solution

  1. Step 1: Check file handling steps

    The code opens the file with fopen and reads with textscan, but does not close the file.
  2. Step 2: Validate format and usage

    The format '%s %d' is valid for reading a string and an integer. textscan supports mixed types. fopen with 'r' is correct for reading.
  3. Final Answer:

    The file is not closed after reading. -> Option C
  4. Quick Check:

    Always fclose after fopen [OK]
Hint: Always fclose after reading files [OK]
Common Mistakes:
  • Forgetting to close the file
  • Thinking '%s %d' is invalid format
  • Confusing fopen modes
5. You have a text file records.txt with mixed data: a name (string), age (integer), and height (float) on each line, separated by commas, like:
John,25,5.9
Anna,30,5.5
Mike,22,6.1
Which MATLAB approach correctly reads this file into a table with proper data types?
hard
A. Use readtable('records.txt', 'Delimiter', ',', 'Format', '%s%d%f')
B. Use readtable('records.txt') without specifying delimiter
C. Use textscan(fopen('records.txt', 'r'), '%s %d %f', 'Delimiter', ',') and fclose after
D. Use textscan(fopen('records.txt'), '%s %d %f') without closing file

Solution

  1. Step 1: Identify correct reading method for mixed CSV data into table

    readtable automatically detects common delimiters like commas and loads data into a table with inferred types (string for names, double for numbers).
  2. Step 2: Compare options

    Use readtable('records.txt') without specifying delimiter: readtable('records.txt') auto-detects comma delimiter. Use readtable('records.txt', 'Delimiter', ',', 'Format', '%s%d%f') uses invalid 'Format' parameter (readtable lacks it). Use textscan(fopen('records.txt', 'r'), '%s %d %f', 'Delimiter', ',') and fclose after: textscan syntax invalid ('Delimiter' not for fid), returns cell array not table. Use textscan(fopen('records.txt'), '%s %d %f') without closing file: textscan fails to parse commas (default whitespace), no fclose.
  3. Final Answer:

    Use readtable('records.txt') without specifying delimiter -> Option B
  4. Quick Check:

    readtable = auto delimiter + table types [OK]
Hint: readtable auto-detects CSV delimiters into tables [OK]
Common Mistakes:
  • Using textscan expecting table output
  • Adding invalid 'Format' to readtable
  • Omitting delimiter handling in textscan
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard