MATLAB: How to find all integers between two integers

homeworkintegersnumbersrand

Write a function called int_col that has one input argument, a positive integer n that is greater than 1, and one output argument v that is a column vector of length n containing all the positive integers smaller than or equal to n, arranged in such a way that no element of the vector equals its own index. In other words, v(k) is not equal to k for any valid index k.

Best Answer

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,
[6 1 2 3 4 5]
or
[3 1 2]
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:
lookfor circular
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:
[n,1:(n-1)]