% Code to plot simulation results from sscfluids_cyl_closed_circuit
%% Plot Description:
%
% This plot shows the position of the piston and the flow rate through the
% pump.

% Copyright 2019 The MathWorks, Inc.

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

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

plotPositionFlow(simlog_sscfluids_cyl_closed_circuit)



% Plot piston position and pump flow rate
function plotPositionFlow(simlog)

% Get simulation results
t = simlog.Cylinder.P.series.time;
x_piston = simlog.Cylinder.P.series.values('m');
x_cmd = simlog.PS_Subtract.I1.series.values('m');
mdot_pump = simlog.Pump.mdot_A.series.values('kg/s');

% Plot results
handles(1) = subplot(2, 1, 1);
plot(t, x_cmd, 'LineWidth', 1)
hold on
plot(t, x_piston, 'LineWidth', 1)
hold off
grid on
legend('Command', 'Measured', 'Location', 'best')
ylabel('Position (m)')
title('Piston Position')

handles(2) = subplot(2, 1, 2);
plot(t, mdot_pump, 'LineWidth', 1)
grid on
ylabel('Mass Flow Rate (kg/s)')
xlabel('Time (s)')
title('Pump Flow Rate')

linkaxes(handles, 'x')

end