Skip to content

csvread

Reading an array from a CSV file

csvread(fname)

  • It reads an array from a CSV file named fname.
  • The file should contain only numerc values (i.e., real and complex numbers); non-numeric data cannot be read.
  • fname should be a character vector representing the name of the file to be read.
  • It only reads files of extensions csv, dat, and txt.

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

a=rand(3,4)
fname='./../csv/data/a.csv';
csvwrite(fname,a);
b=csvread(fname)
a = 1e-1 ×
 8.452   9.059   6.624   8.596
 9.679   8.034   0.183   6.887
 0.980   7.559   6.545   7.754

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

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

b = 1e-1 ×
 8.452   9.059   6.624   8.596
 9.679   8.034   0.183   6.887
 0.980   7.559   6.545   7.754

csvread(fname, r1, c1)

  • fname is as described above.
  • The index r1 is a non-negative real integer, specifying the first row of the CSV file to be read. r1=0 refers to the first row in the file. r1 should be less than the number of rows in the file.
  • The index c1 is a non-negative real integer, specifying the first column of the CSV file to be read. c1=0 refers to the first column in the file. c1 should be less than the number of columns in the file.

Example 2: Reading an array from a CSV file, starting from the third row (r1=2) and the second column (c1=1).

a=rand(3,4)
fname='./../csv/data/a.csv';
csvwrite(fname,a);
b=csvread(fname,2,1)
a = 1e-1 ×
 7.477   4.001   0.084   3.789
 0.297   8.877   6.255   7.504
 1.033   0.067   5.767   1.423

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

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

b = 1e-1 ×
 0.067   5.767   1.423

csvread(fname, r1, c1, [r1 c1 r2 c2])

  • fname is as described above.
  • The indexes r1 and r2 are non-negative real integers, specifying the starting and final rows to be read, respectively. Zero refers to the first row in the file, and r1 and r2 should be less than the number of rows in the file. Moreover, r1<=r2 should hold.
  • r1 in the second and the last arguments should have the same values.
  • The indexes c1 and c2 are non-negative real integers, specifying the starting and final columns to be read, respectively. Zero refers to the first column in the file, and c1 and c2 should be less than the number of columns in the file. Moreover, c1<=c2 should hold.
  • c1 in the third and the last arguments should have the same values.

Example 3: Reading the last row (r1=2, r2=2) and columns 2-3 (c1=1,c2=2) of a CSV file.

a=rand(3,4)
fname='./../csv/data/a.csv';
csvwrite(fname,a);
b=csvread(fname,2,1,[2 1 2 2])
a = 1e-1 ×
 4.496   3.148   9.530   0.040
 4.412   8.323   5.474   3.422
 0.176   3.053   3.370   0.978

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

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

b = 1e-1 ×
 3.053   3.370