function objectivevalue = yagi_objective_function2(y,parasiticVals,freq,elang)
% yagi_objective_function2 returns the objective for a 6-element Yagi
% objective_value = yagi_objective_function(y,parasiticvals,freq,elang)
% assigns the appropriate parasitic dimensions, parasiticvals, to the Yagi
% antenna y, and uses the frequency freq and angle pair elang to calculate
% the objective function value.

% The yagi_objective_function2 function is used for an internal example.
% Its behavior might change in subsequent releases, so it should not be
% relied upon for programming purposes.

% Copyright 2014-2018 The MathWorks, Inc.

bw1 = elang(1);
bw2 = elang(2);
y.ReflectorLength = parasiticVals(1);
y.DirectorLength = parasiticVals(2:y.NumDirectors+1);
y.ReflectorSpacing = parasiticVals(y.NumDirectors+2);
y.DirectorSpacing = parasiticVals(y.NumDirectors+3:end);
output = calculate_objectives(y,freq,bw1,bw2);
output = output.MaxDirectivity + output.FB;
objectivevalue= -output; % To maximize
end

function output = calculate_objectives(y,freq,bw1,bw2)
%calculate_objectives calculate the objective function
% output = calculate_objectives(y,freq,bw1,bw2) Calculate the directivity
% in az = 90 plane that covers the main beam, sidelobe and backlobe.
% Calculate the maximum directivity, sidelobe level and backlobe and store
% in fields of the output variable structure.
[es,~,el] = pattern(y,freq,90,0:1:270);   
el1 = el < bw1;                           
el2 = el > bw2;                           
el3 = el>bw1&el<bw2;
emainlobe = es(el3);
esidelobes =([es(el1);es(el2)]);
Dmax = max(emainlobe);
SLLmax = max(esidelobes);
Backlobe = es(end);
F = es(91);
B = es(end);
F_by_B = F-B;
output.MaxDirectivity= Dmax;
output.MaxSLL = SLLmax;
output.BackLobeLevel = Backlobe;
output.FB = F_by_B;
end