Passing .txt file with datetime & numbers

Viewed 29

I am trying to import a .txt file in Matlab ( random row sample below) and I want to extract the date times from the fisrt 2 columns in one array (yyyy-mm-dd hh-mm-ss ) and the other variables in seperate arrays. Any help would be greatly appreciated. Thanks in advance!

[2018-09-02 23:43:28   25081.98851852   6814.4920 0.0003411   87.40215    8.98677   92.81546  299.03342

]

1 Answers

You can use textscan to read the data in any format, and obtain all the columns in a cell array. This will result in your case in a 1x9 cell array, where each cell will contain the data per row.

% load file and scan the text
fileID = fopen('data.txt');
text_data = textscan(fileID,'%s %s %f %f %f %f %f %f %f');
fclose(fileID);

% obtain date and time in string format
date_cell = cell2mat([text_data{1} repmat({' '}, size(text_data{1})) text_data{2}]);

% convert to datetime
dates = datetime(date_cell,'InputFormat','yyyy-MM-dd HH:mm:ss');

% convert rest of data to matrix
data = [text_data{3:end}];

Use %s to import the dates and times as strings, and %f to import the other columns as doubles.

repmat({' '}, size(text_data{1})) creates a column with spaces, to separate the date and time to concatenate the strings, and convert them to datetimes.

Related