Bird
Raised Fist0
MATLABdata~10 mins

CSV file handling in MATLAB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - CSV file handling
Open CSV file
↓
Read header line
↓
Read each data line
↓
Parse line into values
↓
Store values in array/table
↓
Repeat until end of file
↓
Close file
This flow shows how MATLAB reads a CSV file line by line, parses values, stores them, and closes the file.
Execution Sample
MATLAB
filename = 'data.csv';
fileID = fopen(filename, 'r');
header = fgetl(fileID);
data = [];
while ~feof(fileID)
  line = fgetl(fileID);
  values = sscanf(line, '%f,%f,%f');
  data = [data; values'];
end
fclose(fileID);
This code opens a CSV file, reads the header, then reads and parses each data line into a numeric array.
Execution Table
StepActionVariable ValuesOutput/Effect
1Open file 'data.csv'fileID = valid file handleFile opened for reading
2Read header lineheader = 'A,B,C'Header line stored
3Check end of filefeof(fileID) = falseContinue loop
4Read next lineline = '1.0,2.0,3.0'Line read as string
5Parse linevalues = [1.0; 2.0; 3.0]Values converted to numbers
6Append to datadata = [1.0 2.0 3.0]Data array updated
7Check end of filefeof(fileID) = falseContinue loop
8Read next lineline = '4.0,5.0,6.0'Line read as string
9Parse linevalues = [4.0; 5.0; 6.0]Values converted to numbers
10Append to datadata = [1.0 2.0 3.0; 4.0 5.0 6.0]Data array updated
11Check end of filefeof(fileID) = trueExit loop
12Close filefileID = closedFile closed
💡 End of file reached, loop stops reading lines
Variable Tracker
VariableStartAfter Step 4After Step 6After Step 8After Step 10Final
fileIDundefinedvalid handlevalid handlevalid handlevalid handleclosed
headerundefined'A,B,C''A,B,C''A,B,C''A,B,C''A,B,C'
lineundefined'1.0,2.0,3.0''1.0,2.0,3.0''4.0,5.0,6.0''4.0,5.0,6.0''4.0,5.0,6.0'
valuesundefinedundefined[1.0;2.0;3.0][1.0;2.0;3.0][4.0;5.0;6.0][4.0;5.0;6.0]
data[][][1.0 2.0 3.0][1.0 2.0 3.0][1.0 2.0 3.0; 4.0 5.0 6.0][1.0 2.0 3.0; 4.0 5.0 6.0]
Key Moments - 3 Insights
Why do we use fgetl(fileID) instead of fscanf for reading lines?
fgetl reads one line as a string, allowing us to parse it manually. fscanf reads formatted data but may skip lines or not handle mixed data well. See steps 2,4,8 in execution_table.
Why do we transpose values with values' before appending to data?
sscanf returns a column vector; transposing makes it a row vector to append as a new row in data. See steps 5 and 6.
What stops the while loop from running forever?
feof(fileID) returns true when the file end is reached, causing the loop to exit. See steps 3,7,11.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, what is the content of data?
A[]
B[1.0; 2.0; 3.0]
C[1.0 2.0 3.0]
D[4.0 5.0 6.0]
💡 Hint
Check the 'Variable Values' column at step 6 in execution_table.
At which step does the loop stop reading lines from the file?
AStep 10
BStep 11
CStep 12
DStep 9
💡 Hint
Look for feof(fileID) becoming true in execution_table.
If the CSV file had 4 columns instead of 3, how would the sscanf format string change?
A'%f,%f,%f,%f'
B'%f,%f'
C'%f,%f,%f'
D'%f'
💡 Hint
sscanf format string matches the number of columns; see code in execution_sample.
Concept Snapshot
CSV file handling in MATLAB:
- Open file with fopen(filename, 'r')
- Read header line with fgetl(fileID)
- Loop: read each line with fgetl
- Parse line with sscanf(line, '%f,%f,%f')
- Append parsed data to array
- Close file with fclose(fileID)
Full Transcript
This example shows how MATLAB reads a CSV file step-by-step. First, the file is opened for reading. Then the header line is read and stored. The program enters a loop where it checks if the end of file is reached. If not, it reads the next line as a string. This line is parsed into numbers using sscanf with a format matching the CSV columns. The parsed numbers are transposed and appended as a new row to the data array. This repeats until the end of the file is reached, then the file is closed. Variables like fileID, header, line, values, and data change values as the program runs. Key points include using fgetl to read lines, transposing parsed values to append rows, and using feof to stop the loop. The visual quiz tests understanding of data content after steps, loop exit condition, and format string for parsing.

Practice

(1/5)
1. Which MATLAB function is best suited to read numeric data from a CSV file into a matrix?
easy
A. csvread
B. readtable
C. readmatrix
D. load

Solution

  1. Step 1: Understand the data type

    Numeric data is best handled as a matrix in MATLAB.
  2. Step 2: Choose the appropriate function

    readmatrix is designed to read numeric CSV data directly into a matrix.
  3. Final Answer:

    readmatrix -> Option C
  4. Quick Check:

    Numeric CSV data = readmatrix [OK]
Hint: Use readmatrix for numeric CSV files quickly [OK]
Common Mistakes:
  • Using readtable for purely numeric data
  • Using load which is for MAT files
  • Confusing csvread with readmatrix (csvread is older)
2. Which of the following is the correct syntax to write a matrix A to a CSV file named data.csv in MATLAB?
easy
A. writetable('data.csv', A);
B. writecsv(A, 'data.csv');
C. csvwrite(A, 'data.csv');
D. writematrix(A, 'data.csv');

Solution

  1. Step 1: Identify the correct function for matrix writing

    writematrix is the modern function to write numeric matrices to CSV files.
  2. Step 2: Check syntax correctness

    The syntax writematrix(A, 'data.csv'); correctly specifies the matrix and filename.
  3. Final Answer:

    writematrix(A, 'data.csv'); -> Option D
  4. Quick Check:

    Write matrix to CSV = writematrix [OK]
Hint: Use writematrix(matrix, filename) to save numeric CSV [OK]
Common Mistakes:
  • Using non-existent function writecsv
  • Using csvwrite which is outdated
  • Using writetable for numeric matrix without conversion
3. What will be the output of the following MATLAB code?
A = [1, 2; 3, 4];
writematrix(A, 'test.csv');
B = readmatrix('test.csv');
disp(B);
medium
A. [1 2; 3 4]
B. [1 2 3 4]
C. [1; 2; 3; 4]
D. Error: File not found

Solution

  1. Step 1: Write matrix to CSV

    The matrix A is saved as a 2x2 CSV file with rows [1,2] and [3,4].
  2. Step 2: Read matrix from CSV

    readmatrix reads the CSV back into the same 2x2 numeric matrix.
  3. Final Answer:

    [1 2; 3 4] -> Option A
  4. Quick Check:

    Write and read matrix preserves shape [OK]
Hint: writematrix and readmatrix keep matrix shape intact [OK]
Common Mistakes:
  • Expecting a single row vector output
  • Confusing disp output format with array shape
  • Assuming file read error without saving first
4. Consider this MATLAB code snippet:
T = readtable('data.csv');
writetable(T, 'output.csv');

If data.csv contains mixed numeric and text data, what is a common error to watch for?
medium
A. Using csvwrite to write tables causes incorrect output
B. Using writetable on a numeric matrix causes syntax error
C. Forgetting to close the file after reading causes runtime error
D. Using readmatrix instead of readtable causes syntax error

Solution

  1. Step 1: Understand data type in CSV

    Mixed numeric and text data require table format to preserve all data correctly.
  2. Step 2: Identify correct write function

    csvwrite only supports numeric data and will fail or produce incorrect output for tables.
  3. Final Answer:

    Using csvwrite to write tables causes incorrect output -> Option A
  4. Quick Check:

    csvwrite not for tables = error [OK]
Hint: Use writetable for mixed data, not csvwrite [OK]
Common Mistakes:
  • Using readmatrix for mixed data losing text
  • Assuming file must be closed manually in MATLAB
  • Using writetable on numeric matrix without conversion
5. You have a CSV file with columns: Name (text), Age (numeric), and Score (numeric). You want to read it, increase all Score values by 10%, and save the updated data back to a CSV file. Which MATLAB code snippet correctly does this?
hard
A. data = csvread('file.csv'); data(:,3) = data(:,3) * 1.1; csvwrite('file.csv', data);
B. T = readtable('file.csv'); T.Score = T.Score * 1.1; writetable(T, 'file.csv');
C. T = readtable('file.csv'); T(:,3) = T(:,3) * 1.1; writetable(T, 'file.csv');
D. A = readmatrix('file.csv'); A(:,3) = A(:,3) * 1.1; writematrix(A, 'file.csv');

Solution

  1. Step 1: Read mixed data correctly

    Use readtable to read CSV with text and numeric columns preserving all data types.
  2. Step 2: Update the numeric Score column

    Access the Score column by name and multiply by 1.1 to increase by 10%.
  3. Step 3: Save updated table back to CSV

    Use writetable to save the modified table preserving text and numeric data.
  4. Final Answer:

    T = readtable('file.csv'); T.Score = T.Score * 1.1; writetable(T, 'file.csv'); -> Option B
  5. Quick Check:

    Mixed data update = readtable + modify column + writetable [OK]
Hint: Use readtable and writetable for mixed data updates [OK]
Common Mistakes:
  • Using readmatrix loses text column
  • Trying to multiply table columns by index incorrectly
  • Using csvread/csvwrite which don't support text
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