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:
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:
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:
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:
% 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:
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.
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.