MATLAB: Circular indexing of an array

arrayindexing

I have run into this a number of times in a recent project I'm working on and was wondering what good solutions are out there. What happens is I often have an array representing positions on a line.
X = 1:10;
I want to create a function that indexes the code and circularly wraps around such that when I go through the first iteration of my loop idx-1 = 0 is interpreted as a 10 instead.
for i = 1:10
(X(i-1)+X(i))/2
end
I've tried appending the end element of the array on to the beginning.
X = [10 1:10]
for i = 2:11
...
Seems kind of like an ugly solution though. Any other suggestions?
Thanks!

Best Answer

wrapN = @(x, N) (1 + mod(x-1, n));
N = length(X);
for i = 1:10
(X(wrapN(i-1,N))+X(wrapN(i,N)))/2
end