% Code to plot simulation results from sdl_transmission_5spd
%% Plot Description:
%
% The plot below shows the shaft speeds for the engine, load, and
% intermediate gears.  As the transmission shifts between the gears, the
% load speed matches the speed of different gears in the transmission. When
% the reverse gear is engaged, the speed of the output shaft is negative.

% Copyright 2016 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sdl_transmission_5spd.Load_Inertia.I.w.series.time;
simlog_wLoad = simlog_sdl_transmission_5spd.Load_Inertia.I.w.series.values('rpm');
simlog_wEngine = simlog_sdl_transmission_5spd.Engine.F.w.series.values('rpm');

temp_gearIds = simlog_sdl_transmission_5spd.Transmission.childIds;
temp_gearInds = find(~cellfun(@isempty,regexp(temp_gearIds,'Gear_\d')));
simlog_wGear = zeros(length(simlog_t),length(temp_gearInds));
for temp_geari=1:length(temp_gearInds)
    simlog_wGear(:,temp_geari) = eval(['simlog_sdl_transmission_5spd.Transmission.' temp_gearIds{temp_gearInds(temp_geari)} '.B.w.series.values(''rpm'');']); 
    temp_legstr{temp_geari} = strrep(temp_gearIds{temp_gearInds(temp_geari)},'_',' ');
end


% Plot results
plot(simlog_t, simlog_wLoad, 'LineWidth', 3)
hold on
plot(simlog_t, simlog_wEngine, 'LineWidth', 3)
plot(simlog_t, simlog_wGear, 'LineWidth', 1)
hold off
grid on
title('Shaft Speed')
ylabel('Speed (RPM)')
legend({'Load','Engine',temp_legstr{:}},'Location','Best');
xlabel('Time (s)')

% Remove temporary variables
clear simlog_t 
clear simlog_wLoad simlog_wEngine simlog_wGear
clear temp_gearIds temp_gearInds temp_geari temp_legstr

