Matlab

How to Export a Matrix as a CSV File in MATLAB?

In MATLAB, a matrix refers to a rectangular arrangement of numbers. It is possible to save a matrix as a CSV (Comma-Separated Values) file, which is a type of text file that stores values separated by commas. This feature is handy for sharing data with different programs or importing data into other applications.

How to Export a Matrix as a CSV File in MATLAB

Following two ways can convert a matrix to a CSV file in MATLAB:

Using the csvwrite Function

To export any MATLAB matrix, we can use a simple built-in function called csvwrite. The MATLAB csvwrite function can be used as:

csvwrite(filename, matrix)

Where the filename is the name of the file that we want to create, and the matrix is the matrix that we want to export.

Below MATLAB code will create a new CSV file containing all entities of matric A. The new file name will be my_matrix.csv:

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

csvwrite('my_matrix.csv', A);

Here in the image below, we can see a new CSV file is created in the current working directory of MATLAB.

After opening the CSV file in Excel, we can see a 3×3 matrix displayed.

Using the writematrix Function

The writematrix function is another built-in function that we can use to export a matrix as a CSV file. The writematrix() function has the below-mentioned syntax:

writematrix(matrix, filename)

Where the filename is the name of the file that we want to create, and the matrix is the matrix that we want to export.

For example, the following code would export the matrix A to a file called my_matrix.csv using writematrix() function:

m = [1 2 3 4 5;10 9 8 7 6];

% Exporting to csv file

writematrix(m, 'my_matrix.csv')

Exporting a 4X5 Matrix with Floating Point Data in CSV File

To export a 4×5 matrix with floating-point data to a CSV file in MATLAB, we can use the writematrix() function.

Here is a simple MATLAB example code that exports a 4×5 matrix to a CSV file named data.csv:

% Create a sample matrix

matrix = rand(4, 5);

% Export the matrix to a CSV file

writematrix(matrix, 'data.csv');

In this example, rand(4, 5) generates a 4×5 matrix with random floating-point values between 0 and 1. Next writematrix() function will write the MATLAB matrix to a new file named data.csv.

A screenshot of a computer Description automatically generated

Conclusion

Here we covered how one can export a matrix as a CSV. We have covered two main methods: the csvwrite() function and the writematrix() function. Both functions in MATLAB can convert any matrix into a CSV file. Once the functions are executed the output is generated inside the current working directory of MATLAB.

About the author

Kashif

I am an Electrical Engineer. I love to write about electronics. I am passionate about writing and sharing new ideas related to emerging technologies in the field of electronics.