Read csv file into two ouput variables - text & numbers

7 Ansichten (letzte 30 Tage)
Michael
Michael am 5 Feb. 2015
Bearbeitet: Stephen23 am 6 Feb. 2015
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?
  1 Kommentar
Michael
Michael am 5 Feb. 2015
Update
I have tried using csvread to load in each part separately like so:
numb = csvread(file,1:2,2:5); text = csvread(file,1:2,1);
However, I get the following message:
Error using dlmread (line 139)
Header lines must be integer-valued.
Any ideas? is there something I am missing?

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Guillaume
Guillaume am 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 Kommentare
Michael
Michael am 5 Feb. 2015
nope...unfortunately the latest version of matlab I can use is 2013a
Guillaume
Guillaume am 5 Feb. 2015
Then you will have to use textscan:
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));

Melden Sie sich an, um zu kommentieren.


Stephen23
Stephen23 am 6 Feb. 2015
Bearbeitet: Stephen23 am 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.

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by