# Difference between $\tt rand()$ and $\tt randn()$ in MATLAB [closed]

1. rand() is for "Uniformly distributed pseudorandom numbers"

I generate two rand arrays, and then use the cross-correlation (xcorr2) and the normalized cross correlation (normxcorr2) as follows:

a = rand(512,512);
b = rand(512,512);
c = xcorr2(a,b);
d = normxcorr2(a,b);


The results are as follows:

in which there is strong correlation in the xcorr2().

2. randn() is for "Normally distributed pseudorandom numbers"

The same as the above:

a = randn(512,512);
b = randn(512,512);
c = xcorr2(a,b);
d = normxcorr2(a,b);


and the results are:

Then, my question is why there is apparent difference of xcorr2() for the two random data?

The reason for the difference is that rand() has an output range of $[0,1]$, and therefore you have a constant in both $a$ and $b$ in the first example. The other function randn() generates an output with zero mean. The constants are correlated. Try

a = -0.5 + rand(512,512);
b = -0.5 + rand(512,512);


or

a = rand(512,512);
b = rand(512,512);
a = detrend(a,'constant');
b = detrend(b,'constant');


and see if that is more like what you would expect...

• Thank you, you are right. it is the cross correlation of the two dc signals.
– lxg
May 29 '16 at 7:06