Create unique terms vector
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!