% Code to plot simulation results from sdl_engine_braking
%% Plot Description:
%
% This plot shows how the engine speed changes with the applied throttle
% and with the number of cylinders that are used for engine braking.

% Copyright 2016 The MathWorks, Inc.

% Generate simulation results if they don't exist
if ~exist('simlog_sdl_engine_braking', 'var')
    sim('sdl_engine_braking')
end

% Reuse figure if it exists, else create new figure
if ~exist('h1_sdl_engine_braking', 'var') || ...
        ~isgraphics(h1_sdl_engine_braking, 'figure')
    h1_sdl_engine_braking = figure('Name', 'sdl_engine_braking');
end
figure(h1_sdl_engine_braking)
clf(h1_sdl_engine_braking)

% Get simulation results
simlog_t = simlog_sdl_engine_braking.Inertia.I.w.series.time;
simlog_engineW = simlog_sdl_engine_braking.Inertia.I.w.series.values('rpm');
simlog_engineThr = simlog_sdl_engine_braking.Engine_with_Brake.Engine.T.series.values;
simlog_engineNBrCyl = simlog_sdl_engine_braking.Engine_with_Brake.Braking_Torque.Num_Cyl_Round.O.series.values;

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
plot(simlog_t, simlog_engineW, 'LineWidth', 1)
grid on
title('Engine Speed')
ylabel('Speed (RPM)')

simlog_handles(2) = subplot(2, 1, 2);
yyaxis left
plot(simlog_t, simlog_engineThr, 'LineWidth', 1)
ylabel('Throttle (0-1)')
set(gca,'YLim',[-0.2 1.2]);
yyaxis right
plot(simlog_t, simlog_engineNBrCyl, 'LineWidth', 1)
ylabel('# Braking Cyl (0-8)')
set(gca,'YLim',[-0.2 8.2]);
grid on
title('Throttle and Brake')
xlabel('Time (s)')

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_engineW simlog_engineNBrCyl simlog_engineThr