%% Import Mixed Data from Text File into Table
% This example shows how to use the readtable function to import mixed data from a text file into a table. Import the data into a table, (optionally) specify the data types of the variables, and then append the data with a new variable.
%% Sample File Overview
% The sample file, outages.csv, contains data representing electric utility outages in the US. The file contains six columns. The first line in the file lists column titles for the data. These are the first few lines of the file:
% Region,OutageTime,Loss,Customers,RestorationTime,Cause
% SouthWest,2002-01-20 11:49,672,2902379,2002-01-24 21:58,winter storm
% SouthEast,2002-01-30 01:18,796,336436,2002-02-04 11:20,winter storm
% SouthEast,2004-02-03 21:17,264.9,107083,2004-02-20 03:37,winter storm
% West,2002-06-19 13:39,391.4,378990,2002-06-19 14:27,equipment fault
%
%% Read Text File
% Call readtable to read the file. The function automatically detects the delimiter and the variable types. Display the first five rows.

T = readtable('outages.csv');
T(1:5,:)

%
%% Specify the Variable Data Types Before Import
% To control the data types of the variables, you can manually specify the data types by using import options or the Format name-value pair.
% Create an import options object opts for the file and specify the data types for the variables using the VariableTypes property. Then, use readtable with opts to import the data.

opts = detectImportOptions('outages.csv');
opts.VariableTypes = {'categorical','datetime','double',...
                          'double','datetime','categorical'};
T = readtable('outages.csv',opts);
T(1:5,:)

%
% Alternatively, use the Format name-value pair. to tell readtable to read the first and last columns in the file as categorical data, the second and fifth columns as formatted date and time data, and the third and fourth columns as floating-point values. In the %{yyyy-MM-dd HH:mm}D specifier, the text between the curly braces describes the format of the date and time data.

formatSpec = '%C%{yyyy-MM-dd HH:mm}D%f%f%{yyyy-MM-dd HH:mm}D%C';
T = readtable('outages.csv','Format',formatSpec);

%
% View the first five rows of the table. The table contains different types of data. The first and last variables are categorical arrays, the second and fifth variables are datetime arrays, and the remaining variables are numeric data.

T(1:5,:)

%
%% Modify Imported Data
% Modify the format of the datetime columns in T.

T.OutageTime.Format = 'dd-MMM-yyyy HH:mm:ss';
T.RestorationTime.Format = 'dd-MMM-yyyy HH:mm:ss';

%
% View the first five rows and first four variables of the table.

T(1:5,1:4)

%
%% Append to Imported Data
% Calculate the duration of each electrical outage and append the data to the table.

T.Duration = T.RestorationTime - T.OutageTime;

%
% View the first five rows of the data in the Duration column of T.

T.Duration(1:5)

%
% Copyright 2012 The MathWorks, Inc.