Reading or Writing CSV Files with Matlab
In this friendly tutorial, I'm going to show you how to effortlessly open a CSV file for reading or writing in MATLAB. Let's dive right in!
First off, let's understand what a CSV file is. These files are super handy for transferring data between different software applications. CSV stands for Comma Separated Values, as the data is divided by commas. You'll find that CSV files are commonly used by spreadsheet and database programs to import or export data.
You can read or write data in CSV format using the convenient functions csvwrite() and csvread().
This means you can smoothly export and import data from spreadsheets and databases. It's a piece of cake
Creating CSV Files
Let's jump into a practical example.
Start by defining a 3x3 matrix in the variable M.
>> M = [1 2 3; 4 5 6; 7 8 9]
M =
1 2 3
4 5 6
7 8 9
Now, to save the data in matrix M to a CSV file, simply use the csvwrite() function.
>> csvwrite("matrix.csv", M)
This function requires two parameters:
- The name of the CSV file you want to create.
- The name of the variable to be saved.
Voilà! The csvwrite() function generates a CSV file on your computer containing the data from matrix M.
Now you can easily export the data processed in Matlab and transfer it to other software, like Excel.
Reading CSV Files
To read a CSV file, all you need is the csvread() function. It's a Breeze!
Just provide the name of the CSV file to be read, enclosed in quotes or apostrophes.
>> A = csvread("matrix.csv")
A =
1 2 3
4 5 6
7 8 9
The csvread() function reads the data in the CSV file and then assigns it to variable A in the MATLAB workspace.
And there you have it! You can now import data created by other software or languages (e.g., Excel, Calc, SQL, Python, etc.) into Matlab with ease. Happy coding!