function [z,sse] = fitcurve(x,y)

%normalize
y = y / sum(y);

start_point = rand(1,1);
model = @expfun;
[z,sse] = fminsearch(model,start_point,[],x,y);

pl = plot(x,y,'r');
hold on;
y_mod= x .^ -z;
%y_mod = y_mod / sum(y_mod); %for normalization presented at the exercises
plot(x,y_mod,'g');
legend('Data', 'Model');

    function sse  = expfun(gamma,x,y)
        curve = x .^ -gamma;
        % curve = curve / sum(curve); %Normalization step presented in the
                                      %exercise session.
                                      %This improves the fit, but  the model should give a reasonable fit
                                      %without normalization, too. The
                                      %scale-free model P(k) = k ^ (- gamma) should be
                                      %understood as an approximative
                                      %model, so the normalization is not
                                      %really necessary to judge whether a
                                      %distribution is scale-free.
                                
        error = curve - y;
        sse = sum(error.^2)
    end
end