Simon
Simon

Reputation: 5039

Matlab : Read a file name in string format from a .csv file

I am having a .csv file which contains let's say 50 rows.

At the beginning of each row I have a file name in the following format 001_02_03.bmp followed by values separated by commas. Something like this :

001_02_03.bmp,20,30,45,10,40,20

Can someone tell me how can I read the first column from the data?

I know how to obtain the data from the second column onward. I am using the csvread function like this X = csvread('filename.csv', 0, 1);. If I try to read the first column in the same manner it outputs an error, saying the csvread does not support string format.

Upvotes: 1

Views: 1964

Answers (1)

Colin T Bowers
Colin T Bowers

Reputation: 18560

Use textscan, ie:

fid1 = fopen(csvFileName);
X = textscan(fid1, '%s%f%f%f%f%f%f', 'Delimiter', ',');
fclose(fid1);
FirstCol = X{1, 1};

A little more detail? csvread only works with purely numeric data, so you can't use it to get in data with a .bmp, or underscores for that matter. Thus we use textscan. The funny looking format string input to textscan is just saying that the columns are, in order, of type string %s, then the next 6 columns are of type double %f%f%f%f%f%f (or you might choose to alter this to reflect an integer datatype - I personally rarely bother unless the quantity of data is huge or floating point precision is a problem).

Note, if you just wanted to get the first column and ignore the rest, you can replace the format string with %s% %*[^\n]. A final point, if your csv file has a header line, you can skip it using the HeaderLines optional input to textscan.

Upvotes: 2

Related Questions