How to Write to CSV in MATLAB

by Michael Carroll

Comma-separated value (CSV) files are text files that contain data separated by commas and line breaks. A matrix, for example, might be stored in a CSV file containing as many lines as there are rows, each line containing the row's elements separated by commas. CSV files are useful because they are easily readable both for humans using a plain-text editor and for computer programs. Use the "csvwrite" command in MATLAB to store a matrix in a CSV file.

Define a simple three-by-three matrix by typing the following command into the MATLAB command window: x = [[1 2 3];[4 5 6];[7 8 9]];

Write the matrix x to a CSV file called csvtest.txt using the following command: csvwrite('csvtest.txt',x) The .txt extension is a reasonable choice for your CSV file, since CSV files can be read by a plain text editor. Another common extension is .dat. The contents of the file do not depend on the file extension you choose. The file is saved to your default MATLAB directory, and appears in the "Current Directory" pane on your MATLAB desktop.

Add two optional arguments t "csvwrite to offset the matrix with commas within the file: csvwrite('csvtest.txt',x,2,0) The two arguments correspond to row and column offset. The preceding example adds two empty rows of commas to the top of the file. The following command places the beginning of the matrix in the fifth column on the second row: csvwrite('csvtest.txt',x,1,4)

About the Author

Michael Carroll is a high school mathematics teacher. He has written for various websites since 2010, specializing in programming, web design, electronics and various pieces of software. He holds a bachelor's degree in electrical engineering from the University of Texas, with specialization in embedded system design.