%Econ202B HW#4 Two-sided Lack of Commitment Model Anton Cheremukhin
close all;  clear all;  clc;
y=0.2:0.1:0.8;  beta=0.6;   N=40;
s=zeros(N,1);   w_s=zeros(N,1);     c_s=zeros(N,7);
%Case 1: different gammas
for i=1:N
    gamma=0.05+(i-1)*0.1;       s(i)=gamma;
    wmax=y(4);      wmin=y(1);
    %step 1: compute autarky level of utility
    uy=(y.^(1-gamma))/(1-gamma);    ua=uy*ones(7,1)/(7*(1-beta));
    %find cutoff level by bisection
    while abs(wmin-wmax)>0.0001
        w=(wmin+wmax)/2;
        %iterate over w => compute corresponding consumption bundle
        c=min(max(y,w*ones(size(y))),(1-w)*ones(size(y)));        
        %compute u(c) and the l.h.s. of the binding condition
        uc=(c.^(1-gamma))/(1-gamma);
        uwr=(((1-w)^(1-gamma))/(1-gamma)) + beta*uc*ones(7,1)/(7*(1-beta));
        if uwr<beta*ua+uy(7)       %compare with autarky level
            wmax=w;
        else
            wmin=w;
        end
    end     %when found the cutoff store it
    w_s(i)=w;
    c_s(i,:)=c;
end
%plot results for different values of gamma
figure(1);
plot(s,c_s(:,1),s,c_s(:,2),s,c_s(:,3),s,c_s(:,4),s,c_s(:,5),s,c_s(:,6),s,c_s(:,7),...
                'LineWidth',2)
title('gamma differs, beta=0.6')
ylabel('consumption bundle')
xlabel('gamma')
ylim([0 1])

%Case 2: Different betas
gamma=2;        
for i=1:N
    beta=0.0125+(i-1)*0.025;            s(i)=beta;
    wmax=y(4);      wmin=y(1);
    %step 1: compute autarky level of utility
    uy=(y.^(1-gamma))/(1-gamma);    ua=uy*ones(7,1)/(7*(1-beta));
    %find cutoff level by bisection
    while abs(wmin-wmax)>0.0001
        w=(wmin+wmax)/2;
        %iterate over w => compute corresponding consumption bundle
        c=min(max(y,w*ones(size(y))),(1-w)*ones(size(y)));
        %compute u(c) and the l.h.s. of the binding condition
        uc=(c.^(1-gamma))/(1-gamma);
        uwr=(((1-w)^(1-gamma))/(1-gamma)) + beta*uc*ones(7,1)/(7*(1-beta));
        if uwr<beta*ua+uy(7)       %compare with autarky level
            wmax=w;
        else
            wmin=w;
        end
    end     %when found the cutoff store it
    w_s(i)=w;
    c_s(i,:)=c;
end
%plot results for different values of gamma
figure(2);
plot(s,c_s(:,1),s,c_s(:,2),s,c_s(:,3),s,c_s(:,4),s,c_s(:,5),s,c_s(:,6),s,c_s(:,7),...
                'LineWidth',2)
title('gamma=2, beta differs')
ylabel('consumption bundle')
xlabel('beta')
ylim([0 1])

c=y;
w=0.45;
c=min(max(y,w*ones(size(y))),(1-w)*ones(size(y)));