Sonu Mishra
Sonu Mishra

Reputation: 1779

Reading .csv file into MATLAB

As a part of my assignment, I have to read a .csv file. The file contains a mixture of text, numeric data and missing data under the columns: Number, Title, Description (>100 words, variable length), Location, Time, Term, Company, Category, Source.

There are more than 0.5 million rows.

Suggest me a command to read this file into MATLAB.

I have already tried the following:

uiopen('filename.csv',1)

It gives error: Use textscan to read more complex formats. Then I tried:

data =textscan('filename.csv','%f %s %s %s %s %s %s %s %s %f','HeaderLines', 1, 'Delimiter', ',');

This command runs to completion, but it only gives an array (1X10) of cells (which are empty). Hence, I am not getting what I want.

I also tried textread command but it gives error.

Upvotes: 0

Views: 2389

Answers (2)

Rob
Rob

Reputation: 66

You may want to try using readtable:

t = readtable('filename.csv');

This will create a table in Matlab, which can contain the strings and numeric data.

Alternatively, you can use the Import Tool (accessible from the Import Data button on the Matlab UI), or you can use uiimport to open it:

uiimport('filename.csv')

This will present a graphical presentation of your data, and can generate code for you to do the import as well.

The difficulty you may face with textscan is that you need to get the formats (%f, %s, etc...) correct, and any variations in this may cause failures. For example, if you have strings in a numeric field because of some missing/bad data, it may fail. If you choose to use textscan and don't get the results you're expecting, you may want to try with all '%s' format specifications.

textscan(f,'%s %s %s %s %s %s %s %s %s %s','HeaderLines', 1, 'Delimiter', ',');

Upvotes: 1

mfbutner
mfbutner

Reputation: 141

textscan is what you want to use but according to the matlab documentation page for textscan the first argument is supposed to be a file id. Right now you are passing in a string.

Upvotes: 4

Related Questions