How can I use csvread to read the first 2 columns of a file with variable number of rows?

2 vues (au cours des 30 derniers jours)
I have a csv file that I need to read that has 3 columns (first 2 are data, third is text), but I only want to read in the first 2 columns. There are an unknown number of rows. I tried specifying a RANGE such as [0, 0, :, 1], but that throws a syntax error. Is this something that's possible with a standard csvread call, or do I need to dlmread or textscan everything, then throw out the stuff I don't want?
EDIT: I've also tried using a RANGE of [0, 0, inf, 1], but that seems to still be trying to read the third column, which is text, and throws the error:
Error using dlmread (line 139)
Mismatch between file and format string.
Trouble reading number from file (row 1u, field 3u) ==> Shot 1\n

Réponse acceptée

David Barry
David Barry le 17 Mai 2013
Using csvread it's not possible to specify what you need to do. You can either specificy the start row and column to read from and then all corresponding rows/columns will be read or you can specify a range to read from. The range solution would obviously enable you to skip the third text column which is what is causing the error but you won't be able to simply just read all lines using this method.
The best way would be to use textscan as you suggested.
Example:
Suppose I have the following csvfile which is called test.csv in my current directory
6,2,a
2,3,b
3,4,c
Then I would use the following code to read it in. Note that the * character excludes reading in the string column.
fid = fopen('test.csv');
data = textscan(fid,'%f %f %*s','Delimiter',',');
fclose(fid);
  1 commentaire
Stephen
Stephen le 20 Mai 2013
Thanks, this was just what I was looking for; something fast, simple, and small.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by