Unique random number (between 1 and 40)

5 ビュー (過去 30 日間)
Josefine
Josefine 2014 年 2 月 20 日
コメント済み: Parisa 2021 年 1 月 4 日
I wish for a vector consisting of 30 numbers. I want those numbers to be between 1 and 40 BUT NOT with the same number appearing more than once.
I have found this:
clear all; close all; clc n=30; number=zeros(1,n); %Generates my vector for i=1:n number(1,i)=ceil(rand()*40); %B = ceil(A) rounds the elements of A to the nearest integers greater %than or equal to A. For complex A, the imaginary and real parts are rounded independently. end
My problems begin when I want to verify that the figure/value/number in number(i) does not exist in any other location (number(:)) and IF it does, I want it to give me a new random number.
I have attempted every sort of if-for-while-loops, added within the initial loop as well as applied onto the generated number-vector, I can think of and I either get syntax errors or a neatly looking code that does not do what I want.
I would be most grateful for help.
/Josefine

採用された回答

Wayne King
Wayne King 2014 年 2 月 20 日
編集済み: Wayne King 2014 年 2 月 20 日
Why not just use randperm()
x = randperm(40);
If you want to randomly select a subset
K = 10;
x = randperm(40,K);
  2 件のコメント
Josefine
Josefine 2014 年 2 月 20 日
I also just found this, which seems to work better for my version of MATLAB
n=40;
k=30;
[idx,idx]=sort(rand(1,n));
out=idx(1:k)
Parisa
Parisa 2021 年 1 月 4 日
Hi, your code help me a lot, thanks

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by