user2005253
user2005253

Reputation:

How to read csv files in matlab as you would in R?

I have a data set that is saved as a .csv file that looks like the following:

Name,Age,Password
John,9,\i1iiu1h8
Kelly,20,\771jk8
Bob,33,\kljhjj

In R I could open this file by the following:

X = read.csv("file.csv",header=TRUE)

Is there a default command in Matlab that reads .csv files with both numeric and string variables? csvread seems to only like numeric variables.

One step further, in R I could use the attach function to create variables with associated with teh columns and columns headers of the data set, i.e.,

attach(X)

Is there something similar in Matlab?

Upvotes: 8

Views: 7190

Answers (3)

mjeppesen
mjeppesen

Reputation: 1099

Matlab's new table class makes this easy:

X = readtable('file.csv');

By default this will parse the headers, and use them as column names (also called variable names):

>> x

x = 

 Name      Age     Password  
_______    ___    ___________

'John'      9     '\i1iiu1h8'
'Kelly'    20     '\771jk8'  
'Bob'      33     '\kljhjj' 

You can select a column using its name etc.:

>> x.Name

ans = 

    'John'
    'Kelly'
    'Bob'

Available since Matlab 2013b. See www.mathworks.com/help/matlab/ref/readtable.html

Upvotes: 3

Stanislav
Stanislav

Reputation: 2677

I liked this approach, supported by Matlab 2012.

path='C:\folder1\folder2\';
data = 'data.csv';
data = dataset('xlsfile',sprintf('%s\%s', path,data));

Of cource you could also do the following:

[data,path] = uigetfile('C:\folder1\folder2\*.csv');
data = dataset('xlsfile',sprintf('%s\%s', path,data));

Upvotes: 0

Colin T Bowers
Colin T Bowers

Reputation: 18560

Although this question is close to being an exact duplicate, the solution suggested in the link provided by @NathanG (ie, using xlsread) is only one possible way to solve your problem. The author in the link also suggests using textscan, but doesn't provide any information about how to do it, so I thought I'd add an example here:

%# First we need to get the header-line
fid1 = fopen('file.csv', 'r');
Header = fgetl(fid1);
fclose(fid1);

%# Convert Header to cell array
Header = regexp(Header, '([^,]*)', 'tokens');
Header = cat(2, Header{:});

%# Read in the data
fid1 = fopen('file.csv', 'r');
D = textscan(fid1, '%s%d%s', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid1);

Header should now be a row vector of cells, where each cell stores a header. D is a row vector of cells, where each cell stores a column of data.

There is no way I'm aware of to "attach" D to Header. If you wanted, you could put them both in the same structure though, ie:

S.Header = Header;
S.Data = D;

Upvotes: 6

Related Questions