Importing data in secs to matlab

I used Matlab to extract response times from an array of sensors, which I inserted into a table as follows:
Line 1: Concentration, Sensor 1, Sensor 2, Sensor 3;
Line 2: 1,2.3 secs, 3.2 secs, 3.4 secs;
Line 3:3,2.3 secs, 3.2 secs, 3.4 secs;
How do I get rid of the secs and just display a number? Furthermore, how do I import data of this format (i.e. 4 secs) back into matlab?

4 Comments

In regard to the second question, I want to know how to import as a duration array.
What is actually in the table (I presume that means a file?) IOW, is the 'Line N' string there or are you just showing us content of each record?
In the columns labeled 'Sensor n' each data point is a duration formatted in seconds. Hence, the 'secs'. This table was exported to a .txt file. I now want to import it back into matlab but either maintain the duration format or alternatively convert these seconds to numbers. i.e. 1.53 secs = 1.53. The 'line N' was to specify the row and is not in the table.
Line 1 displays the variable names.

Sign in to comment.

Answers (2)

Simon, there's not currently a way to use readtable to create a duration array directly from a file. If you are the one creating the csv file, and you're doing it using writetable, perhaps you could call the seconds function like this
t.Sensor1 = seconds(t.Sensor1);
and then write out the modified table. Then when reading it back in, reverse the process (using exactly the same command -- seconds converts both ways).
If you are not the one creating the file, but the format is consistent, you could read them as strings, strip off the 'secs' part using strrep, and then convert to numeric using str2double.
Ryan Simpson
Ryan Simpson on 10 May 2017
Edited: Ryan Simpson on 10 May 2017
Simon,
Details on textscan can be found here.
Here is what I was able to come up with, please note that I didn't include any handling for NaNs or missing values.
% Path to your file
filename = 'test.txt';
% Open the file
fileID = fopen(filename);
% Read in the header text
header = textscan(fileID,'%s',4,'Delimiter',',');
% Read in the data
data = textscan(fileID,'%d %f secs %f secs %f secs;','Delimiter',[',']);
% Close the file
fclose(fileID);
% Format the header so it will work with variable names
header = header{1};
header = strrep(header,' ','');
header = strrep(header,';','');
% Create a new table to store data
SensorData = table(data{1},data{2},data{3},data{4},'VariableNames',header);
% If you want to store data as seconds replace the line above with the
% following
%SensorData = table(data{1},seconds(data{2}),seconds(data{3}),seconds(data{4}));
And you don't have to use tables but I find them very handy.

Categories

Asked:

on 10 May 2017

Answered:

on 10 May 2017

Community Treasure Hunt

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

Start Hunting!