lettura simple

How to Open, Read, and Write a CSV File in Octave

In this tutorial, I'll explain how to read and save data in CSV format in Octave.

What is CSV format? WhatCSV format is a widely-used data exchange format between different software programs. It is called CSV because values are separated by commas (comma-separated values). It's commonly used to export or import data to spreadsheets such as Excel or Calc, as well as in databases.

In Octave, you can save and read data in CSV format. Additionally, you can import CSV data from a spreadsheet and save it to a variable.

Creating a CSV File

Let's take a practical example.

Create a 3x3 matrix:

>> M = [1 2 3; 4 5 6; 7 8 9]
M =
1 2 3
4 5 6
7 8 9

To save the matrix M in a CSV file, use the csvwrite() function.

Specify the file name in the first parameter and the object you want to save in the second parameter. In this case, the object is the matrix M.

>> csvwrite("matrix.csv", M)

The matrix is now saved in the "matrix.csv" file.

Opening and Reading a CSV File

Now, let's try to read the CSV file you just created using the csvread() function.

Write the file name in quotes or single quotes in the first parameter of the function.

>> A = csvread("matrix.csv")
A =
1 2 3
4 5 6
7 8 9

The csvread() function reads the contents of the "matrix.csv" file and assigns the data to the variable A.

This is how you can open, read, and save data in CSV format using Octave.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin