How do you calculate a correlation function in MATLAB?

I am trying to calculate the correlation function given by
where I sum over all i ("part" in the following). Do I just choose time zero arbitrarily as t1 like in the following? I am not sure how to do this. vbar is calculated separately and is just a constant here..
for t1 = 1:tmax
for t2 = t1:tmax
for part = 1:tot_part
a0(t2-t1,part) = a0(t2-t1,part) + (v(t1,part)+vbar)*(v(t2,part)+vbar)
n0(t1,part) = (v(t1,part)+vbar) + 1
end
end
end
for t = 0:tmax-1
for part = 1:tot_part
corr0(t) = corr0(t) + a0(t,part)/n0(t,part)
end
end

Answers (1)

If you want to calculate "auto correlation", see xcorr.
You may need to devide the result by var.

6 Comments

Just a few lines of code server for this problem.
@Hiro Not quite, it's essentially an autocorrelation function with a constant subtracted from each x(t)
so what about using xcorr with a single argument?
You should take a look at the documentation carefully. I would do it like:
x = rand(10,1)
x = 10×1
0.6315 0.4384 0.3091 0.8854 0.2887 0.0139 0.3035 0.0960 0.7033 0.1798
[r,lag] = xcorr(x)
r = 19×1
0.1136 0.5230 0.4245 0.6103 0.8461 0.5727 1.0507 1.0046 1.1730 2.1822
lag = 1×19
-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9
stem(lag,r/var(x))
Does this make sense to you?
Thanks, yes, it would nice though if it would be possible to understand this without resorting first things first to the xcorr function, which is why I had the clunky for loops in my post.
Totally understood. When I was in school, I didn't realize there had been this function for ages and crafted my own from scratch but good thing about MATLAB is that you can avoid "re-inventing wheels".

Sign in to comment.

Products

Release

R2021b

Asked:

on 31 May 2022

Commented:

on 2 Jun 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!