How to read csv files in matlab as you would in R?
我有一个保存为.csv文件的数据集,如下所示:
1 2 3 4 | Name,Age,Password John,9,\\i1iiu1h8 Kelly,20,\\771jk8 Bob,33,\\kljhjj |
在R中,我可以通过以下方式打开此文件:
1 | X = read.csv("file.csv",header=TRUE) |
Matlab中是否有一个默认命令,可以同时读取带有数字变量和字符串变量的.csv文件?
再进一步,在R中,我可以使用attach函数创建与数据集的列和列标题相关联的变量,即
1 | attach(X) |
Matlab中有类似的东西吗?
尽管这个问题几乎是完全重复的,但@NathanG提供的链接中建议的解决方案(即,使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | %# 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); |
我没有办法将
1 2 | S.Header = Header; S.Data = D; |
Matlab的新表类使这变得容易:
1 | X = readtable('file.csv'); |
默认情况下,这将解析标头,并将其用作列名(也称为变量名):
1 2 3 4 5 6 7 8 9 10 | >> x x = Name Age Password _______ ___ ___________ 'John' 9 '\\i1iiu1h8' 'Kelly' 20 '\\771jk8' 'Bob' 33 '\\kljhjj' |
您可以使用其名称等选择列:
1 2 3 4 5 6 7 |
自Matlab 2013b起可用。
请参阅www.mathworks.com/help/matlab/ref/readtable.html
我喜欢由Matlab 2012支持的这种方法。
1 2 3 |
当然,您还可以执行以下操作:
1 2 |