Read csv file into two ouput variables - text & numbers
6 次查看(过去 30 天)
显示 更早的评论
I have inherited a script that reads in a csv file, where the first column is text and the other columns are numbers. For example the data is similar to this:
hello 1 2 3 4
bye 5 6 7 8
and so forth...
my script includes the following code:
[summary,text] = xlsread(filename)
I understand from an answer related to another question I posted that it is not possible to use 'xlsread' as I am using matlab via linux (the person before me was using Windows) and csv is unsupported when using xlsread. Also, when I attempt to use 'csvread', it does not have the option to create two output variables (summary & text)
Does anyone know another method of loading in a csv file in a similar fashion to the code presented here?
回答(2 个)
Guillaume
2015-2-5
Assuming you're on a 2013b or later, the simplest way to import this sort of file is with readtable. In your case:
t = readtable(filename, 'ReadVariableNames', false, 'ReadRowNames', true);
3 个评论
Guillaume
2015-2-5
fid = fopen(filename, 'rt');
raw = textscan(fid, '%s %f %f %f %f'); %or whatever formatting your file is
fclose(fid);
rownames = raw(:, 1);
data = cell2mat(raw(:, 2:end));
Stephen23
2015-2-6
编辑:Stephen23
2015-2-6
Sadly csvread will only handle numeric data, and as your first column contains strings you will have to use another function, such as textscan . This code gives you an exact replacement of the xlsread functionality (for this usage case, not in general):
fid = fopen(filename,'rt');
C = textscan(fid,'%s%f%f%f%f', 'MultipleDelimsAsOne',true, 'CollectOutput',true);
fclose(fid);
text = C{1};
summary = C{2};
You should have a read through the textscan documentation, as there are many options that you might find useful.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!