%% Problem 1

%---------------------------------------------------------------
% This is the code block for problem 1.  See the results below.
clc
fprintf('Problem 1 Results\n\n')

m=10;       % Mean of the distribution
s=5;        % Standard deviation

%Generate random numbers from a normal distribution with mean of zero,
%standard deviation of 1. Then correct to what I want. 
a=5*randn(1000,1)+10;

% Check the properties of my vector.  
fprintf('The mean of the vector is: %g\n',mean(a))
fprintf('The standard deviation of the vector is: %g\n',std(a))

fprintf('\nThey are close to the distribution mean and standard deviation\n')
fprintf('but are not exact because it is a finite sized vector\n')

fprintf('\nHere is the histogram showing the distribution of our vector\n')

% I use 100 to have more accurate histogram
figure
hist(a,100);  % You can also use 'histogram'
xlabel('Bin Center')
ylabel('Counts')
%----------------------------------------------------------------
 
%% Problem 2

%---------------------------------------------------------------
% This is the code block for problem 2.  See the results below. 
clc
fprintf('Problem 2 Results\n\n')

%Create function handle. 'a' is the vector created in problem 1. 
f=@(x) sum((x-a).^2);

%Plot the function to take a look at where minimum might be


%Function doesn't work if x is a vector, so calculate one at a time

%Initialize variable (not necessary but good practice)
y=zeros(size(Xvec)); 

%Calculate function values over a range.
Xvec=linspace(-20,20,100);
for ii=1:length(Xvec)
    y(ii)=f(Xvec(ii)); 
end

%Plot
figure
plot (Xvec, y,'r')
xlabel('x')     %Always label!
ylabel('f(x)')

fprintf('Looks like minimum is between 0 and 20 so I use that as bounds.\n')

%Create the starting values. A---X0--B
A=0;
B=20;
r=(1+sqrt(5))/2;
X0=(B-A)*r+A;

%Starting X interval positions and function values at those points
X=[A X0 B];
FX=[f(X(1)) f(X(2)) f(X(3))];

%Create object and set properties
GR=HW7_Solution_GoldenSection();
GR.F=f;
GR.X=[A X0 B];
GR.TolX=1e-16;

%Run the method that finds the minimum
GR.findMin()

%Note: We could watch the search finding using 'GR.plotUpdateGS()'
%
%Display this property (Set by finMin() )

fprintf('\nThe found minimum is %g.  I show this on the plot below\n',GR.Found)

%Plot
figure
plot (Xvec, y,'r')
hold on
plot ([GR.Found,GR.Found], [min(y) max(y)],'k--')
xlabel('x')     %Always label!
ylabel('f(x)')
legend('Function','Found Minimum')

fprintf('\nI notice the found minimum: %g is the same as the mean of a:%g\n',GR.Found,mean(a))

%Is this a coincidence?

%---------------------------------------------------------------

%% Problem 3

%---------------------------------------------------------------
% This is the code block for problem 2.  See the results below. 
clc
fprintf('Problem 3 Results\n\n')

%Number of averages over the same ratio.  Function minimums will vary. 
Naverages=1000;

%Number of different ratios to try between 0 and 1
Nratios=20;

%Create array of ratios to test. 
Ratios=linspace(1,2,Nratios);

%Intialize matrix for output
FunctionCalls=zeros(Nratios,Naverages);

%Loop over Ratios
for jj=1:Nratios
    
    %Uncomment this line to show progress
    %fprintf('Calculating for Ratio: %g\n',Ratios(jj))
    
    %Setup for this ratio
    R=Ratios(jj);
    A=0;
    B=1;
    r=R/(1+R);
    X0=(B-A)*r+A;
    
    %Create object and set properties
    GR=HW7_Solution_GoldenSection();
    GR.R=R;
    GR.X=[A X0 B];
    GR.TolX=1e-8;
    
    %'Nested' loop over functions with different (random) minimums
    for ii=1:Naverages
        
        %Create new function with random minimum
        a=rand();
        f = @(x) (x-a).^2;
        
        %Change object property to new function handle
        GR.F=f;
        
        %Reset Bounds
        GR.X=[A X0 B];

        %Run method to find minimum
        GR.findMin()
        
        %Store our result in the matrix
        FunctionCalls(jj,ii)=GR.NFunctionCalls;
    end
end

%Plot the results

%Take average along the second dimension
AverageFC=mean(FunctionCalls,2);

%This is our main result:
fprintf('\nThe plot below is our main resul.:\n')

figure
plot(Ratios,AverageFC,'b')
hold on
%Plot the position of the Golden Ratio
plot([1.618 1.618],[min(AverageFC) max(AverageFC)],'k--')
xlabel('Ratio')
ylabel('Number of Function Calls')


fprintf('Interesting- the golden ratio is not optimal!\n')

%---------------------------------------------------------------

%% Problem 4

% Notice the many 'fprintf' staments used to print text next to figures.
%
% I changed the output file format to 'PDF' and hit publish
%
% I'll also print out the class definition for the class I am using:

type HW7_Solution_GoldenSection



