%% Read Data from MDF-Files
% This example shows you how to read channel data from an MDF-file.
%
%% Open the MDF-file
% Before reading channel data from an MDF-file, open access to the file with the mdf command.

m = mdf("CANapeReadDemo.MF4")

%
%% Specify Data to Read
% The read command is used to retrieve data from the MDF-file with several variations. It requires two primary arguments. One is the numeric index of the channel group from which to read. Second is the name(s) of the channels in the channel group to read. Information about these items is available from the MDF-file.

m.ChannelGroup(1)
m.ChannelNames{1}

%
%% Read a Subset of Data by Index
% To read just a subset of data by index, the index range is provided as input to the read command.

data = read(m, 1, m.ChannelNames{1}, 1, 10)

%
%% Read a Specific Data Value by Index
% Providing a single numeric index argument will retrieve the data values at that index.

data = read(m, 1, m.ChannelNames{1}, 5)

%
%% Read a Subset of Data by Time
% To read a subset of data by time, duration arguments are provided as input to the read command.

data = read(m, 1, m.ChannelNames{1}, seconds(0.50), seconds(0.60))

%
%% Read a Specific Data Value by Time
% Providing a single duration will retrieve the data values at or closest to that timestamp.

data = read(m, 1, m.ChannelNames{1}, seconds(0.55))

%
%% Output Format Defaults to Timetable
% The default output format of the read command is a timetable. This option can also be controlled with the OutputFormat argument.

data = read(m, 1, "Triangle", 1, 10, "OutputFormat", "timetable")

%
%% Output Data as Timeseries
% If a timeseries is desired as output, the OutputFormat can be specified to the read command. When outputting data as a timeseries, only a single channel may be read at a time.

data = read(m, 1, "Triangle", 1, 10, "OutputFormat", "timeseries")

%
%% Output Data as Vectors
% Output from the read command can also be specified as vectors. When outputting data as a vector, only a single channel may be read at a time.

[data, time] = read(m, 1, "Triangle", 1, 10, "OutputFormat", "vector")

%
%% Read an Entire Channel Group
% To quickly read the data from an entire channel group in a single call, no additional arguments are specified to the read command.

data = read(m, 1, m.ChannelNames{1});

%
%% Close the File
% Close access to the MDF-file by clearing its variable from the workspace.

clear m

%
% Copyright 2016-2021 The MathWorks, Inc.