MATLAB: Create unique terms vector

single termuniquevecotr

Hello, I'm quite new to MATLAB and have been given the task to create a vector of a length n and with a maximum value of p, with no terms repeated. I am able to create a function that can determine if a random number generated is already present previously in the vector. However, when it does find there is already such a number, it generates a new one without doing the test again. I put my while loop and can't understand why it doesn't work.
Here's the code if someone could care to explain where is the mistake and why it is so:
for i = 1:n
V(i) = floor(1+Nombre.*rand(1));
for ii = 1:i-1
Egal = isequal(V(i),V(ii));
while Egal == 1
V(i) = floor(1+p.* rand(1));
Egal = isequal(V(i),V(ii));
end
end
end
To make it clear, the problem looks like this
V = 1
V = 1 4
V = 1 4 1
V = 1 4 4 2

Best Answer

When you generate a new V(i), you do not go back and recheck it against previous V(ii)
I recommend that you read up about ismember()