Create unique terms vector

조회 수: 1 (최근 30일)
Maxime
Maxime 2011년 11월 11일
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

채택된 답변

Walter Roberson
Walter Roberson 2011년 11월 11일
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()
  댓글 수: 1
Maxime
Maxime 2011년 11월 11일
Thanks, ismember was perfect, and it simplified everything quite a lot

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2011년 11월 11일
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.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by