i ¼ Alpha þ J - 1; % Get age i ¼ Alpha, Alphaþ1
Wt(i)¼ Wt(i-1)þ A- G(J)*Wt(i-1); % Wt
S(i) ¼ S(i-1)*exp(-(MjþMa*G(J))); % Annual survival
W ¼ W þ a*S(i)*Wt(i)*G(J) ; % Cumulative fitness
end
W¼ -W; % Return negative of fitness
Now function BESTG:
% Function to get best G for consecutive pairs of alpha
function Wdiff ¼ BESTG(alpha)
N ¼ 2; % Nos of mature ages
% Results for alpha Note that G is passed two values
G1 ¼fminsearch(@(G) FITNESS(G,alpha,N),[0.1,0.1]); % Store best G
W1 ¼ -FITNESS(G1,alpha,N); % Fitness
% Results for alphaþ1
G2 ¼fminsearch(@(G)FITNESS( G,alphaþ1,N),[0.1,0.1]);% Store best G
W2 ¼ -FITNESS(G2,alphaþ1,N); % Fitness
W3 ¼ W2-W1; % Diff between fitnesses
% return Wdiff,W1,G1 % G1 will eventually be the best G
Wdiff ¼ [W3, W1, G1];
Main program calls BESTG:
clear all; % Clear the workspace
ALPHA ¼ 5; % Set initial alpha
DIFF ¼ BESTG(ALPHA); % Calculate difference between W at two alphas
while DIFF(1)> 0; % If DIFF[1] > 0 then W still increasing
ALPHA ¼ ALPHAþ1;
DIFF ¼ BESTG(ALPHA);
end
% Out of loop and thus ALPHA is the best
% Print Alpha, Wdif, G1, G2 ...GN
[ALPHA,DIFF(1),DIFF(3),DIFF(4)] %Print out alpha, G, W
OUTPUT: (Same as R)
Ans ¼ 19.0000 00.0003 0.3497 0.4835
To increase the number of ages and hence the number of variables we alter
N in
function BESTG,
and modify the following lines given that we wish to set N ¼ 5
(giving 6 variables to be estimated):
N ¼ 6; % Nos of mature ages
G1 ¼fminsearch(@(G) FITNESS(G,alpha,N), [0.1,0.1,0.1,0.1,0.1,0.1]);
G2 ¼fminsearch(@(G) FITNESS(G,alphaþ1,N),[0.1,0.1,0.1,0.1,0.1,0.1]);
[ALPHA,DIFF(1),DIFF(3),DIFF(4),DIFF(5),DIFF(6)] %Print out
The result is
ans ¼ 18.0000 0.0042 0.2166 0.2463 0.2917 0.3666
164 MODELING EVOLUTION