# Estimating the number of degrees of freedom in a chi-squared distribution

I have generated $n=1000$ samples according to a chi-squared distribution $\chi^2(k)$ using a fixed number of degrees of freedom $k=2$ with MATLAB (chi2rnd function). I just would like to estimate the number of degrees of freedom using maximum likelihood. When calculating the log-likelihood, one should ends up with the following expression:

\begin{align} log(L(k)) & = \log{\left(\prod_{i=1}^n f(x_i;k)\right)}\\ & = \sum_{i=1}^n \log{\left(\frac{x_i^{k/2-1}e^{-x_i/2}}{\Gamma(k/2)2^{k/2}}\right)}\\ & = \left(\frac{k}{2}-1\right)\sum_{i=1}^n \log{x_i} - \frac{1}{2}\sum_{i=1}^n x_i - \log{(\Gamma(k/2))} - \frac{k}{2}\log{(2)} \end{align}

However, when I try to plot the resulting expression as a function of the number of degrees of freedom between $k=0.01$ and $k=10$, I have a linear function that does not reach any maximum:

I simply do not understand why I obtain such a result. I wonder if the error comes from the MATLAB program of if the maximum likelihood approach is not applicable for such a PDF. However, when considering that samples follow a Gamma distribution (with appropriate parameters by fixing one of them), it works as expected. Does anyone know what's wrong?

You probably forgot to multiply last two parts by $n$, so it should be
$$\big(\frac{k}{2}-1\big)\sum_{i=1}^n\log{x_i} - \frac{1}{2}\sum_{i=1}^nx_i - n\log(\Gamma(k/2)) - \frac{nk}{2}\log(2)$$