%% Truss Deflection - Parameter Sweep
% This is a parameter sweep study of the effect of the number of elements
% and element cross sectional area on the displacement at the tip of a
% cantilevered truss.
%
% We are going to truncate our parameter sweep when the peak deflection
% values are less than 85% of max and we're half way through.
%
% Copyright 2015 The MathWorks, Inc.
%

%% Initialize Problem

% Number of elements and cross sectional area of each element
nNum = 20;
aNum = 20;

% Vectors of number of elements and cross section areas to sweep
nVals = (1:nNum)+10; % number of segments, start with 11
aVals = linspace(100, 200, aNum);  % cross sectional area

% Grid of all combinations
[nGrid, aGrid] = meshgrid(nVals, aVals);

% Peak value results matrix
peakVals = nan(nNum,aNum);


%% Parameter Sweep
%
t0 = tic;
for ii = 1:numel(aGrid)
    % Fill futures with parallel tasks
    Y = trussCantilever(nGrid(ii),aGrid(ii)); 

    % Determine peak deflection in Y direction at the tip
    peakVals(ii) = max(Y(:,end));
    
    % Test to see if we can be done, 85% of peak and half way through
    if (peakVals(ii) < 0.017)
        break
    end
end
toc(t0)


%% Visualize results
% Show the parameter sweep grid results

visualizeParamSweep(nVals, aVals, peakVals);


%% Animate Truss Deflection
% Animate the truss over the simulation time at the largest deflection

% Which combination yielded biggest deflection?
[~, idx] = max(peakVals(:));

% Get the full results at this location and animate it
[Yr,bars,L,N,H] = trussCantilever(nGrid(idx),aGrid(idx));
plotTruss(Yr,bars,L,N,H);
