Autocorrelation of a uniform random process i am currently learning the basics of signal processing.

As you may know the definition of the autocorrelation is different if you look at a random process or for example a deterministic signal

My question is about the autocorrelation of random processes:

Suppose $X$ is a random variable with uniform distribution over $[0,1]$

so: $ f_X(x)=1$ for $(0&lt;x&lt;=1)$

The autocorrelation $r_{XX}(n_1,n_2)$ is defined as: $r_{XX}(n_1,n_2)=E[X(n_1)X(n_2)]$.

if $X$ is stationary up to the second order the autocorrelation is only a function of $\tau$: $r_{XX}(\tau)=E[X(n+\tau)X(n)]$.

If i generate such a random variable in matlab with the "rand" command and compute the autocorrelation (which should be possible because the random process is ergodic [ time and ensemble averages are equal]) i get a strange result which looks more like the convolution of the propability density functions. If i subtract the mean i get the result i would expect, because i assume that X is uncorrelated white noise, so $r_{XX}(\tau)=\sigma_x^2\delta(\tau)$



x=rand(1,100)
Rxx=xcorr(x,x);
subplot(2,1,1)
plot(Rxx);
grid;
title('Autocorrelation function of (X)');

ylabel('Autocorrelation');

y=rand(1,100)-0.5
Ryy=xcorr(y,y);
subplot(2,1,2)
plot(Ryy);
grid;
title('Autocorrelation function of (Y)=(X-0.5) ');

ylabel('Autocorrelation');




So my questions are:

$(1)$ Am i wrong with the assumption that $r_{XX}(\tau)=\sigma_x^2\delta(\tau)$? And if yes, how can we compute $r_{XX}(\tau)$ because we don't know the join-propability densitiy function $f_{X_1X_2}(x_1,x_2)$

$(2)$ Why does the result of the first computed autocorrelation look so strange? (first plot)
As suggested I am adding my comments as an answer.
The sample autocorrelation function (ACF) for $n$ observations is given by

$\hat{p}_x(m) = \frac{\sum_{n=0}^{N-m-1}(x_n - \bar{x})(x_{n+m} - \bar{x})}{\sum_{n=0}^{N-m-1}(x_n - \bar{x})^2} $

To understand why you have a difference between figure 1 and figure 2, lets assume we are looking at observations $x_n$ being zero mean. Let be $y_n = x_n +c$ with c being a constant. Looking now at matlabs help for xcorr for the input $y_n$ we get

$r(m)=\sum_{n=0}^{N-m-1}y_n y_{n+m}^* = \sum_{n=0}^{N-m-1}(x_n + c)(x_{n+m} + c)$

which can be summarized to

$\sum_{n=0}^{N-m-1}(x_nx_{n+m}) + (N-m)c^2$

In the case of xcorr $m$ equals $m=-N,...,N$. Which means you are adding a triangle to your result.

To calculate the ACF matlab has the autocorr function, which takes care of normalization and demeaning of the input.