使用matlab分隔字符串读取CSV文件

时间:2014-02-04 20:19:27

标签: matlab csv textscan

我正在尝试使用Matlab读取CSV文件并绘制它。基本上,我想绘制时间与心率的关系。但是,当我使用textscan时,它会将两个列复制到一个列中,我不确定如何将它分开。我想在变量x和变量y的心率中节省时间并绘制它们。

到目前为止我已经这样做了:

clear, clc;
ftoread = 'data.csv';
fid = fopen(ftoread); %Reads the CSV file
data = textscan(fid,'%s%f'); % Read in a string and a double
fclose(fid); % close
for i=2:size(data{1,1},1)% checks for size of the csv file
    x = strnum(data);%i need to separate the time from BPM using the comma thing and string command
    %y = data{2};
end
plot(x,y);

在Matlab的data单元格中,这就是我所看到的:

'Time,BPM(HeartRate)'
'5:55:26,0'
'5:55:26,66'
'5:55:27,69'
'5:55:27,71'
'5:55:27,72'

for循环中,我想将时间分开并将其保存在一个变量中,并将心率设置为不同的变量。

2 个答案:

答案 0 :(得分:1)

您是否需要标题信息'Time,BPM(HeartRate)'textscan有许多不错的功能(请参阅文档)。特别是,你要求它忽略固定数量的标题行,你可以告诉它使用什么分隔符(默认是空格):

data = textscan(fid,'%s%f','Headerlines',1,'Delimiter',',');

现在data{1}的输出将如下所示:

'5:55:26'
'5:55:26'
'5:55:27'
'5:55:27'
'5:55:27'

data{2}将是双值的向量。

答案 1 :(得分:1)

要回答关于如何将时间值读入一个变量以及将读数读入第二个变量的基本问题,请使用:

clear;
clc;
ftoread = 'hr.csv';
fid = fopen(ftoread); %OPENS the CSV file
data = textscan(fid,'%s%f','Headerlines',1,'Delimiter',','); %Reads the file
fclose(fid); % closes the file

x = datenum(data{1}); %Time variables moved to new variable called x
y = data{2}; % Readings moved to variable y

plot(x,y); % plot bp readings vs time

% Create xlabel
xlabel('Time of Reading');

% Create ylabel
ylabel('Blood Pressure Reading');

% Create title
title('Blood Pressure Readings vs Time');

您的数据目前看起来并不多,因为血压读数基本上都记录在同一秒。

要调整您的x值,使它们相对于第一个读数而不是时间的开始,您可以这样做,假设csv条目按顺序排列:

clear, clc;
ftoread = 'hr.csv';
fid = fopen(ftoread); %Reads the CSV file
data = textscan(fid,'%s%f','Headerlines',1,'Delimiter',',');
fclose(fid); % close

x = datenum(data{1});
x = x - x(1); % Times relative to the first recorded time entry
y = data{2};

plot(x,y);

% Create xlabel
xlabel('Seconds since first reading');

% Create ylabel
ylabel('Blood Pressure Reading');

% Create title
title('Blood Pressure Readings vs Time');