Skip to content

csvwrite

Write an array to a CSV file

csvwrite(fname, A)

  • It writes an array A to a CSV file named fname.
  • A can be a real, complex, logical or character array.
  • If ndims(A) is larger than 2, it is first reshaped to a matrix before writing to the file.
  • fname should be a character array representing a file name with extension csv, dat or txt.
  • If a file named fname already exists, it will be overwritten without prior notification.

Example 1: Writing a complex array a to a file, and then read it back as b.

name='./../csv/data/a.csv';
a=complex([1 2 3;4 5 6;7 8 9],[1 2 3;4 5 6;7 8 9])
csvwrite(name,a);
b=csvread(name)
a =
 1.000 + 1.000i   2.000 + 2.000i   3.000 + 3.000i
 4.000 + 4.000i   5.000 + 5.000i   6.000 + 6.000i
 7.000 + 7.000i   8.000 + 8.000i   9.000 + 9.000i

Array written to debug/csv/data/a.csv successfully.

Array read from debug/csv/data/a.csv successfully.

b =
 1.000 + 1.000i   2.000 + 2.000i   3.000 + 3.000i
 4.000 + 4.000i   5.000 + 5.000i   6.000 + 6.000i
 7.000 + 7.000i   8.000 + 8.000i   9.000 + 9.000i

csvwrite(fname, A, r, c)

  • fname and A are as specified above.
  • r is a non-negative real integer specifying the numbers of zero rows appended to the top of the matrix when writing to the file.
  • c is a non-negative real integer specifying the numbers of zero columns appended to the left of the matrix when writing to the file.

Example 2: Writing a complex array a to a file, and then read it back as b. One zero row and 2 zero columns are appended to A when writing to the file. b returned from csvread has an extra row and 2 extra columns of zeros.

name='./../csv/data/a.csv';
a=[1 2 3;4 5 6;7 8 9]
csvwrite(name,a,1,2);
b=csvread(name)
a =
 1.000   2.000   3.000
 4.000   5.000   6.000
 7.000   8.000   9.000

Array written to debug/csv/data/a.csv successfully.

Array read from debug/csv/data/a.csv successfully.

b =
 0.000   0.000   0.000   0.000   0.000
 0.000   0.000   1.000   2.000   3.000
 0.000   0.000   4.000   5.000   6.000
 0.000   0.000   7.000   8.000   9.000