function intgwtdw
% Fig. 4.1 Book code example for int[g(w,t)dw] on [t0,t] 
%   by RNG Simulation (3/2007):
%   Generation is by summing g(W(i),t(i))dW(i) of even spacing dt 
%      for i=0:n, but converted to from index base 0 to base 1:
%      matlab[G(W(i),T(i))DW(i);i=1:N+1]  ...
%             = math[g(W(i),t(i))dW(i);i=0:n].
%   Sample g(w,t) = exp(w-t/2) with exact integral g(w,t) - 1 
%      on [0,t].
clc % clear variables, but must come before globals, 
%         else clears globals too.
clf % clear figures
fprintf('\nfunction intgwtdw OutPut:')
nfig = 0; % figure counter.
TF= 2.0; T0 = 0; N = 20000;  NI = N+1; dt = (TF-T0)/NI; % Set initial 
%                     time grid:  Fixed Delta{t}.
sqrtdt = sqrt(dt); % Set std. Wiener increment time scale.
%
% Begin Sample Path Calculation:
kstate = 1;
randn('state',kstate);  % set randn state for repeatability.
DW = sqrtdt*randn(1,NI); % Generate normal random vector of N+1 
%                          samples for dW(t).
T = zeros(1,NI+1); T(1) = 0;  % set T initially.
W = zeros(1,NI+1);  % Set W(1) in place of W(0) = 0 wpo for base 1 vector.
S = zeros(1,NI+1);  % Set integral sum initially.
gv = zeros(1,NI+1); gv(1) = g(W(1),T(1)); % Set integrand initially.
Err = zeros(1,NI+1); % Set Error initially.
for i = 1:NI % Simulated Sample paths by Increment Accumulation:
    T(i+1) = T(i) + dt;
    W(i+1) = W(i) + DW(i);
    gv(i+1) = g(W(i+1),T(i+1));
    S(i+1) = S(i) + gv(i)*DW(i);% integrand g defined in subfunction.
    Err(i+1) = S(i+1) - (gv(i+1) -gv(1)); % CAUTION: FOR KNOWN g HERE!
end
T(1,NI+1) = TF;  % Correct for final cumulative time rounding errors.
% Begin Plot:
nfig = nfig + 1;
fprintf('\n\nFigure(%i):  int[g](t) versus t Simulations\n',nfig)
figure(nfig);
scrsize = get(0,'ScreenSize'); % figure spacing for target screen
ss = [5.0,4.0,3.5]; % figure spacing factors
plot(T,S,'k-',T,W,'k-.',T,Err,'k--','LineWidth',2);
title('\int g(W,t)dW(t) for g = exp(W(t)-t/2)'...
    ,'FontWeight','Bold','Fontsize',44);
ylabel('\int g(W,t)dW(t), W(t), g(W(t),t) - g(0,0)'...
    ,'FontWeight','Bold','Fontsize',44);
xlabel('t, Time'...
    ,'FontWeight','Bold','Fontsize',44);
hlegend=legend('\int g(W,t)dW(t)','W(t)','Error(t)'...
    ,'Location','SouthWest');
set(hlegend,'Fontsize',36,'FontWeight','Bold');
set(gca,'Fontsize',36,'FontWeight','Bold','linewidth',3);
set(gcf,'Color','White','Position' ...
   ,[scrsize(3)/ss(nfig) 60 scrsize(3)*0.60 scrsize(4)*0.80]); %[l,b,w,h]
% End Main
function gv = g(W,T)
% Example g(W(t),t) = exp(W(t) - t/2); exact integral = g(W(t),t) - 1.
gv = exp(W - T/2);
% End Code
