importing a CSV file in MATLAB

AbbyJ picture AbbyJ · Jan 22, 2012 · Viewed 7.8k times · Source

How can I import a CSV file into MATLAB?. A row in the file i am working with looks like:

SUNW,2-Jan-98,1998,5,40.125,41.5

There are 36 columns and 10107 rows. The first row contains the column headers. It seems that MATLAB doesn't support importing such kind of CSV files. Using the following textscanfunction reads the whole data into one cell array.

data = textscan(fid, '%s %s %d %d %f %f', ...
    'HeaderLines',1, 'Delimiter',',', 'CollectOutput',1);

Is there a way I could read the data into different variable for each column?

Answer

Mansoor Siddiqui picture Mansoor Siddiqui · Jan 22, 2012

Example 6 in the textscan documentation seems to cover the use case that you're interested in:

Using a text editor, create a comma-delimited file data2.csv that contains the lines

    abc, 2, NA, 3, 4
    // Comment Here
    def, na, 5, 6, 7

Designate the input that textscan should treat as comments or empty values:

    fid = fopen('data2.csv');
    C = textscan(fid, '%s %n %n %n %n', 'delimiter', ',', ...
                 'treatAsEmpty', {'NA', 'na'}, ...
                 'commentStyle', '//');
    fclose(fid);

textscan returns a 1-by-5 cell array C with the following cells:

    C{1} = {'abc'; 'def'}
    C{2} = [2; NaN]
    C{3} = [NaN; 5]
    C{4} = [3; 6]
    C{5} = [4; 7]

While it doesn't explicitly assign each column to a separate variable, you can easily do something like col1 = C{1};.