Question

I am trying to read a CSV file using Matlab and plot it. Basically, I would like to plot time vs. heart rate. However, when I use textscan it copies both columns into one and I'm not sure how to separate it. I would like to save time in a variable x and heart rate in a variable y and plot them.

I have done this so far:

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);

in the data cell in Matlab this is what I see:

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

etc.

In the for loop I would like to separate the time and save it in one variable and set heart rate to a different variable.

Was it helpful?

Solution

To answer your basic question of how to read in the time values to one variable, and the readings into a second variable, use this:

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');

Your data currently does not look like much since the blood pressure readings are essentially all recorded at the same second.

To adjust your x-values so they are relative to the first reading and not the beginning of time, you can do this assuming csv entries come in order:

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');

OTHER TIPS

Do you need the header information 'Time,BPM(HeartRate)'? textscan has many nice features (see the documentation). In particular, you ask it to ignore a fixed number of header lines and you can tell it what delimiter to use (the default is whitespace):

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

Now the output of data{1} will look like:

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

and data{2} will be a vector of double values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top