%% Plot Selected States from Simulation Data
% Plot the prey versus predator data from the stochastically simulated lotka model by using a custom function (plotXY).
%
% Load the model. Set the solver type to SSA to perform stochastic simulations, and set the stop time to 3.

sbioloadproject lotka;
cs              = getconfigset(m1);
cs.SolverType   = 'SSA';
cs.StopTime     = 3;
rng('default') % For reproducibility

%
% Set the number of runs and use sbioensemblerun for simulation.

numRuns = 2;
sd      = sbioensemblerun(m1,numRuns);

%
% Plot the simulation data. By default, sbioplot shows the time plot of each species for each run.

sbioplot(sd); 

%
% Plot selected states against each other; in this case, plot the prey population versus the predator population. Use the function plotXY (shown at the end of this example) to plot the simulated y1 (prey) data versus the y2 (predator) data. Specify the function as a function handle.
% If you use the live script file for this example, the plotXY function is already included at the end of the file. Otherwise, you must define the plotXY function at the end of your .m or .mlx file or add it as a file on the MATLAB path.

sbioplot(sd,@plotXY,{'y1'},{'y2'},'xlabel','y1','ylabel','y2','title','Prey versus Predator');

%
%% Define plotXY Function
% sbioplot accepts a function handle for a function with the signature:
% function [handles,names] = functionName(sd,xArgs,yArgs).
% The plotXY function plots two selected states against each other. The first input sd is the simulation data (SimBiology SimData object or vector of objects). In this particular example, xArgs is a cell array containing the name of the species to be plotted on the x-axis, and yArgs is a cell array containing the name of the second species to be plotted on the y-axis. However, you can use the inputs xArgs and yArgs in any way in your custom plotting function. The function returns handles, an array of function handles to the line plots, and names, a cell array of character vectors shown on the nodes that are children of a Run node in a hierarchical display.

function [handles,names] = plotXY(sd,xArgs,yArgs)
    
% Select simulation data for each state from each run.
xData1 = selectbyname(sd(1),xArgs);
xData2 = selectbyname(sd(2),xArgs);
yData1 = selectbyname(sd(1),yArgs);
yData2 = selectbyname(sd(2),yArgs);

% Plot the species against each other.
fH1 = plot(xData1.Data,yData1.Data);
fH2 = plot(xData2.Data,yData2.Data);

% The first output, handles, is a two-dimensional array of handles of the line plots. It must be of size M x N, 
% where M is the number of line plots for each run and N is the number of runs.
handles = [fH1,fH2];

% The second output, names, must be a one-dimensional cell array of character vectors.
% Its length must be equal to the number of rows in handles, and the texts are displayed on the 
% nodes that are children of a Run node.
names = {'y1 vs y2'};
   
end

% Copyright 2019 The MathWorks, Inc.