Create unique terms vector
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuesta aceptada
Walter Roberson
el 11 de Nov. de 2011
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()
Más respuestas (1)
Fangjun Jiang
el 11 de Nov. de 2011
Your algorithm does have a flaw.
Let's say, you've generated 9 unique numbers. For simplicity, let's say the numbers are 1 to 9. Now you are generating the 10th number (i==10), which is 8 in your first attempt. You are doing the check, it passes the check for numbers from 1 to 7. But it didn't pass the check for number 8 (ii==8). So you generate a new number, which is 5. Since V(i) or V(10) is 5, it does not equal V(ii), or V(8) which is 8. So you move on to generate the next number. But apparently, you've duplicated the number 5.
I am not sure what is the purpose of this exercise. Maybe you could generate a large set of numbers first. All of them are less than the maximum. Then you can check for duplication, starting from 1,up to n. If a duplication is found, simply remove it.
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!