Read csv file into two ouput variables - text & numbers
8 views (last 30 days)
Show older comments
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?
Answers (2)
Guillaume
on 5 Feb 2015
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 Comments
Guillaume
on 5 Feb 2015
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
on 6 Feb 2015
Edited: Stephen23
on 6 Feb 2015
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 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!