%% Save Tuned Parameters in MAT File Using Output Function
% Load the recorded sensor data and ground truth data.

load('insfilterAsyncTuneData.mat');

% Create timetables for the sensor data and the truth data.

sensorData = timetable(Accelerometer, Gyroscope, ...
    Magnetometer, GPSPosition, GPSVelocity, 'SampleRate', 100);
groundTruth = timetable(Orientation, Position, ...
    'SampleRate', 100);

% Create an insfilterAsync filter object that has a few noise properties.

filter = insfilterAsync('State', initialState, ...
    'StateCovariance', initialStateCovariance, ...
    'AccelerometerBiasNoise', 1e-7, ...
    'GyroscopeBiasNoise', 1e-7, ...
    'MagnetometerBiasNoise', 1e-7, ...
    'GeomagneticVectorNoise', 1e-7);

% Create a tuner configuration object for the filter. Define the OutputFcn property as a customized function, myOutputFcn, which saves the latest tuned parameters in a MAT file.

config = tunerconfig('insfilterAsync', ...
    'MaxIterations',5, ...
    'Display','none', ...
    'OutputFcn', @myOutputFcn);
config.TunableParameters = setdiff(config.TunableParameters, ...
    {'GeomagneticVectorNoise', 'AccelerometerBiasNoise', ...
    'GyroscopeBiasNoise', 'MagnetometerBiasNoise'});
config.TunableParameters

% Use the tuner noise function to obtain a set of initial sensor noises used in the filter.

measNoise = tunernoise('insfilterAsync')

% Tune the filter and obtain the tuned parameters.

tunedParams = tune(filter,measNoise,sensorData,groundTruth,config);

% Display the save parameters using the saved file.

fileObject = matfile('myfile.mat');
fileObject.params

%
%% The output function

function stop = myOutputFcn(params, ~)
save('myfile.mat','params'); % overwrite the file with latest
stop = false;
end

% Copyright 2020 The MathWorks, Inc.