% Generate code and run the generated executable with different values of
% variant control variable.

%   Copyright 2021 The MathWorks, Inc.

%% Open model
mdl = 'slexVariantParametersStartup';
open_system(mdl);

%% Generate code
slbuild(mdl);

%% Run executable
runExecutable(mdl);

clear mdl;

%% Run the generated executable for different variant control values
function runExecutable(mdl)
    % get the executable name
    exeName = getExecName(mdl);
    
    % Run for VCtrl = 1,2,3,4
    VCtrlVals = 1:4;
    legend_labels = cell(1, 4);
    
    for VC = VCtrlVals
        % update control variable value in file "slexVariantParametersStartup_VCtrl.txt"
        updateVCtrl(VC);
        % run the generated executable
        system(exeName);
    
        % load the results
        load([mdl, '.mat'], 'rt_tout', 'rt_yout');
        % plot the results
        plot(rt_tout, rt_yout.signals.values, 'x-');
        legend_labels{VC} = ['VCtrl = ', num2str(VC)];
        hold on;
    end
    
    % Add titles, labels to the plot
    xlabel('time');
    ylabel('Out1');
    title('Step response for different variant control variable values');
    legend(legend_labels);
    grid on;
    hold off;
end

%% Utility functions
function updateVCtrl(vctrl)
    fileName = 'slexVariantParametersStartup_VCtrl.txt';
    fileattrib(fileName, '+w');
    fileID = fopen(fileName, 'w+');
    fprintf(fileID, '%d', vctrl);
    fclose(fileID);
end

function exeName = getExecName(mdl)
    if ispc
        exeName = [mdl, '.exe'];
    else
        exeName = ['./', mdl];
    end
end
