%% Example Title
% Irrigation channel (WJ. Palm p. 128)
%% Problem # 9
% Name
%% For student to be completed
% Here is an idea, along which one can proceed. Explain what is going on here.
% 
% # Make "intelligent" comments of various phases 
% # Experiment with finer discretization for computation (not much for surf-figures)
% # Restrict domain to see closer
% # Etc, etc.
% # Use fminsearch with initial values you got above.
% # Assure yourself and us that you have found the minimum.
% # Finally draw the optimal irrigation channel
%% Short description

%{
 Irrigation channel ...
%}
%% 
% $$ L=\frac{100}{d} - \frac{d}{\tan \Theta} + \frac{2d}{\sin \Theta}.$$
% 
% We must now find the values of d and  $\Theta$ to minimize L .


%% Solution idea
%
% Define a function handle: For meshgrid we need 
% a function of 2 variables:

channelL=@(d,t) 100./d - d./tan(t) + 2*d./sin(t)

% For fminsearch we need a function of a vector variable 
% (vector of length 2: x=[d,theta])
channelLV=@(x) 100./x(1) - x(1)./tan(x(2)) + 2*x(1)./sin(x(2))
%% 
% 
d=linspace(0,30,30);
t=linspace(0,pi/2,30);
[D,T]=meshgrid(d,t);
Z=channelL(D,T);
%% 
% 
surf(d,t,Z);shg
figure
contour(d,t,Z,30);
hold on
mesh(d,t,Z);colorbar;shg
%clabel(c)
%% 
% 
minZ=min(min(Z))
min_ind=Z==minZ;
minD=D(min_ind)
minT=T(min_ind)
channelL(minD,minT)
%% Apply fminsearch 
% Do some more visualizations, calculations and draw channel,
%

