Ok, so your solution works when n is an even integer. For an odd integer, the middle element of that string will cause it to fail, because it stays unchanged in the permutation you have chosen.
You might also choose a random permutation. Something like this:
vec = 1:n;
ind = 1:n;
while any(vec == ind)
vec = vec(randperm(n));
end
The problem is this might take a while. Have you ever seen the birthday paradox? This is actually a variation of that paradox, in that you will get hits surprisingly often for even moderately sized values of n. (A nice question is how large does n need be so that you will see a problem in more than 50% of the random samplings that you take? What value of n assures a hit over 99% of the time?)
But here is a simple solution that will never fail. Suppose you took the last number, and put it first? So, for example,
or
You get the idea. Just do a circular shift on the vector. Is there a function in MATLAB that does such a thing? Try this:
Does it show any functions in MATLAB that will do a circular shift?
Of course, this is simple enough to do without a built-in function. So you might try this:
Best Answer