How to Read CSV Files in MATLAB: Simple Guide
In MATLAB, you can read CSV files using the
readtable function to get a table or csvread for numeric data. Use readtable('filename.csv') to load the CSV into a table for easy data handling.Syntax
The main functions to read CSV files in MATLAB are:
readtable(filename): Reads the CSV file into a table, which can hold mixed data types.csvread(filename): Reads numeric data from a CSV file into a matrix.readmatrix(filename): Reads numeric and text data into a matrix or array.
Use filename as a string with the CSV file path.
matlab
T = readtable('data.csv'); M = csvread('data.csv'); A = readmatrix('data.csv');
Example
This example shows how to read a CSV file named sample.csv into a table and display its contents.
matlab
filename = 'sample.csv'; % Create a sample CSV file fid = fopen(filename, 'w'); fprintf(fid, 'Name,Age,Height\nAlice,30,5.5\nBob,25,6.0\nCarol,27,5.7\n'); fclose(fid); % Read CSV into a table T = readtable(filename); % Display the table disp(T);
Output
Name Age Height
_____ ___ ______
'Alice' 30 5.5
'Bob' 25 6
'Carol' 27 5.7
Common Pitfalls
Common mistakes when reading CSV files in MATLAB include:
- Using
csvreadon files with text headers causes errors because it expects only numbers. - Not specifying the correct file path or filename leads to file not found errors.
- Ignoring mixed data types;
csvreadcannot handle text, so preferreadtableorreadmatrixfor mixed data.
Example of wrong and right usage:
matlab
% Wrong: Using csvread on CSV with headers % M = csvread('sample.csv'); % This will error % Right: Use readtable instead T = readtable('sample.csv');
Quick Reference
| Function | Description | Use Case |
|---|---|---|
| readtable(filename) | Reads CSV into a table | Best for mixed data types and headers |
| csvread(filename) | Reads numeric data only | Use for numeric-only CSV without headers |
| readmatrix(filename) | Reads numeric and text data | Flexible for mixed data, newer alternative |
Key Takeaways
Use readtable to read CSV files with headers and mixed data types.
csvread works only for numeric data without headers and is less flexible.
Always check the file path and name to avoid file not found errors.
readmatrix is a modern alternative that handles mixed data well.
Creating a sample CSV file helps test your reading code quickly.