Xara
Xara

Reputation: 9098

Reading specific column from CSV file in matlab

I am trying to read a CSV file in matlab. I just want to read the second column but the code below prints out everything on CSV file. What parameters or functions I have to introduce to make it read just the second column

FILENAME = 'C:\Users\Desktop\Results.csv';

fid = fopen(FILENAME, 'rt');
a = textscan(fid, '%s', 'HeaderLines',1,'Delimiter',',');
fclose(fid);
celldisp(a)

Upvotes: 6

Views: 21211

Answers (1)

Shai
Shai

Reputation: 114786

There are several ways:

  1. Using cvsread:
    Assuming you have N rows in the file1:

    a = csvread( FILENAME, 0, 1, [0 1 N-1 1 ] );
    
  2. You might also consider xlsread

    a = xlsread( FILENAME, 'B:B' );  
    

    See specific example on the xlsread doc.

  3. Another option is dlmread

    a = dlmread( FILENAME, ',', [0 1 N-1 1] );
    

1 - A nice (and fast) way to count the number of lines in the file in Matlab can be found in this answer by Rody Oldenhuis.

Upvotes: 8

Related Questions