% Code to plot simulation results from sdl_vehicle_manual_transmission
%% Plot Description:
%
% The plots below show the speeds of various shafts in the drivetrain.  The
% output shaft speed is equal to the speed of the gear whose synchronizer
% is engaged.  The engine stays in appropriate speed speed range even
% though the vehicle is accelerating because of the chosen gear.

% Copyright 2016 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sdl_vehicle_manual_transmission.Engine.F.w.series.time;
simlog_wEngine = simlog_sdl_vehicle_manual_transmission.Engine.F.w.series.values('rpm');
simlog_wTransOut = simlog_sdl_vehicle_manual_transmission.Differential_Gear.B.w.series.values('rpm');

if (simlog_sdl_vehicle_manual_transmission.Transmission.hasChild('Detailed'))
    simlog_wGears(:,1) = simlog_sdl_vehicle_manual_transmission.Transmission.Detailed.Gear_1.F.w.series.values('rpm');
    simlog_wGears(:,2) = simlog_sdl_vehicle_manual_transmission.Transmission.Detailed.Gear_2.F.w.series.values('rpm');
    simlog_wGears(:,3) = simlog_sdl_vehicle_manual_transmission.Transmission.Detailed.Gear_3.F.w.series.values('rpm');
end

% Plot results
plot(simlog_t, simlog_wTransOut, 'LineWidth', 3)
hold on
plot(simlog_t, simlog_wEngine, 'LineWidth', 1)
temp_legendstr = {'Trans. Out.', 'Engine'};
if (simlog_sdl_vehicle_manual_transmission.Transmission.hasChild('Detailed'))
    plot(simlog_t, simlog_wGears, 'LineWidth', 1)
    temp_legendstr = [temp_legendstr(:)' {'Gear 1'},{'Gear 2'},{'Gear 3'}];
end
hold off
grid on
title('Shaft Speeds')
ylabel('Speed (RPM)')
xlabel('Time (s)')
legend(temp_legendstr,'Location','Best');

% Remove temporary variables
clear simlog_t temp_legendstr
clear simlog_wTransOut simlog_wEngine simlog_wGears
