How to Import Selected Rows or Columns into MATLAB

By Jim Sizemore, John Paul Mueller

Sometimes you don’t need an entire file imported into MATLAB, only certain rows and columns of it. The csvread() function provides a straightforward example of how to perform this task.

To see just a range of data displayed, type CSVOutput = csvread(‘NumericData.csv’, 0, 0, [0, 0, 1, 1]) and press Enter. You see the following output:

CSVOutput =
 15 25
 18 29

The first argument to csvread() is the name of the file to read. The second and third arguments are the row and column to start reading. In this case, the example starts with row 0 and column 0. The fourth argument is a matrix that specifies the range of values to read.

The first two values in the matrix must match the second and third argument because they specify the starting point of the range. The second two values provide the ending point of the range.

To give you a better idea of precisely how the range feature works, type CSVOutput = csvread(‘NumericData.csv’, 0, 1, [0, 1, 2, 2]) and press Enter. This time the output changes to show the second and third columns of the data in NumericData.csv:

CSVOutput =
 25 30
 29 33
 35 41

The row and column values that you use with csvread() are zero based. This means that the first row is actually row 0 and the first column is actually column 0. A three-row table would have rows 0 through 2, not 1 through 3. Likewise, a three-column table would contain columns 0 through 2, not 1 through 3.