필터 지우기
필터 지우기

Read csv file into two ouput variables - text & numbers

조회 수: 2 (최근 30일)
Michael
Michael 2015년 2월 5일
편집: Stephen23 2015년 2월 6일
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일
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일
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일
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.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by