%% Confirm and Delete Track in Multi-Object Tracker
% Create a sequence of detections of a moving object. Track the detections using a multiObjectTracker System object™. Observe how the tracks switch from tentative to confirmed and then to deleted.
% Create a multi-object tracker using the initcakf filter initialization function. The tracker models 2-D constant-acceleration motion. For this motion model, the state vector is [x;vx;ax;y;vy;ay].

tracker = multiObjectTracker('FilterInitializationFcn',@initcakf, ...
    'ConfirmationThreshold',[3 4],'DeletionThreshold',[6 6]);

%
% Create a sequence of detections of a moving target using objectDetection. To use these detections with the multiObjectTracker, enclose the detections in a cell array.

dt = 0.1;
pos = [10; -1];
vel = [10; 5];
for detno = 1:2
    time = (detno-1)*dt;
    det = { ...
        objectDetection(time,pos, ...
        'SensorIndex',1, ...
        'ObjectAttributes',{'ExampleObject',1}) ...
        };
    [confirmedTracks,tentativeTracks,allTracks] = tracker(det,time);
    pos = pos + vel*dt;
    meas = pos;
end

%
% Verify that the track has not been confirmed yet by checking the number of confirmed tracks.

numConfirmed = tracker.NumConfirmedTracks

%
% Because the track is not confirmed, get the position and velocity from the tentativeTracks structure.

positionSelector = [1 0 0 0 0 0; 0 0 0 1 0 0];
velocitySelector = [0 1 0 0 0 0; 0 0 0 0 1 0];
position = getTrackPositions(tentativeTracks,positionSelector)
velocity = getTrackVelocities(tentativeTracks,velocitySelector)

%
% Add more detections to confirm the track.

for detno = 3:5
    time = (detno-1)*dt;
    det = { ...
        objectDetection(time,pos, ...
        'SensorIndex',1, ...
        'ObjectAttributes',{'ExampleObject',1}) ...
        };
    [confirmedTracks,tentativeTracks,allTracks] = tracker(det,time);
    pos = pos + vel*dt;
    meas = pos;
end

%
% Verify that the track has been confirmed, and display the position and velocity vectors for that track.

numConfirmed = tracker.NumConfirmedTracks
position = getTrackPositions(confirmedTracks,positionSelector)
velocity = getTrackVelocities(confirmedTracks,velocitySelector)

%
% Let the tracker run but do not add new detections. The existing track is deleted.

for detno = 6:20
    time = (detno-1)*dt;
    det = {};
    [confirmedTracks,tentativeTracks,allTracks] = tracker(det,time);
    pos = pos + vel*dt;
    meas = pos;
end

%
% Verify that the tracker has no tentative or confirmed tracks.

isempty(allTracks)

% Copyright 2012 The MathWorks, Inc.