0
0
MATLABdata~5 mins

CSV file handling in MATLAB

Choose your learning style9 modes available
Introduction
CSV files are simple text files that store data in rows and columns. Handling CSV files lets you read data into MATLAB or save your results to share with others.
You want to load data from a spreadsheet into MATLAB for analysis.
You need to save your MATLAB results so others can open them in Excel.
You want to exchange data between MATLAB and other programs easily.
You have data in a text format and want to process it in MATLAB.
You want to create reports or logs in a simple, readable format.
Syntax
MATLAB
data = readmatrix('filename.csv');
writematrix(data, 'filename.csv');
Use readmatrix to read numeric data from a CSV file into a matrix.
Use writematrix to save a matrix or array back to a CSV file.
Examples
Reads numeric data from 'data.csv' into the variable data.
MATLAB
data = readmatrix('data.csv');
Saves the matrix data into a file named 'output.csv'.
MATLAB
writematrix(data, 'output.csv');
Reads data from 'data.csv' into a table, useful for mixed data types.
MATLAB
T = readtable('data.csv');
Writes the table T to a CSV file named 'output.csv'.
MATLAB
writetable(T, 'output.csv');
Sample Program
This program creates a 2x3 matrix, saves it to 'mydata.csv', then reads it back and displays it.
MATLAB
data = [10, 20, 30; 40, 50, 60];
writematrix(data, 'mydata.csv');
readData = readmatrix('mydata.csv');
disp(readData);
OutputSuccess
Important Notes
If your CSV file contains text or mixed data, use readtable and writetable instead of readmatrix and writematrix.
Make sure the CSV file is in your current folder or provide the full path.
MATLAB automatically handles commas as separators in CSV files.
Summary
Use readmatrix and writematrix for numeric CSV data.
Use readtable and writetable for mixed or text data.
CSV files are easy to share and work with in MATLAB.