Read csv file into two ouput variables - text & numbers

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 件のコメント

Michael
Michael 2015 年 2 月 5 日
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?

サインインしてコメントする。

回答 (2 件)

Guillaume
Guillaume 2015 年 2 月 5 日

0 投票

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 件のコメント

Michael
Michael 2015 年 2 月 5 日
I am using 2012b unfortunately, although I may be able to change versions. Is there an equivalent function for 2012b?
Michael
Michael 2015 年 2 月 5 日
nope...unfortunately the latest version of matlab I can use is 2013a
Guillaume
Guillaume 2015 年 2 月 5 日
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));

サインインしてコメントする。

Stephen23
Stephen23 2015 年 2 月 6 日
編集済み: Stephen23 2015 年 2 月 6 日

0 投票

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.

製品

質問済み:

2015 年 2 月 5 日

編集済み:

2015 年 2 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by