フィルターのクリア

How can I generate a random vector between 1-9 with 10 numbers and at least one number should be >2.

3 ビュー (過去 30 日間)
X=rand(10,1)*(9-1)+1 How should I change this code to make at least one number >2.

採用された回答

John D'Errico
John D'Errico 2014 年 12 月 21 日
編集済み: John D'Errico 2014 年 12 月 21 日
Generate 9 (NINE) random numbers with no constraint from 1:9. Then generate a 10th number that is assuredly greater than 2. Randomly permute the set.
R = [ceil(rand(1,9)*9), ceil(rand*7 + 2)];
R = R(randperm(10));
Easy peasy. If you prefer to use randi, it is just as easy, and perhaps easier to read.
R = [randi([1 9],[1 9]), randi([3,9],1)];
R = R(randperm(10));
The general idea is a common one to be found in probability. If you need one number to have some property, then generate it as such.
Edit: to generate real numbers instead of integers...
R = [rand([1 9])*8 + 1, rand(1)*7 + 2];
R = R(randperm(10));
The basic idea remains the same. Note that the rand function generates a value in the strict open interval (0,1), so the result of our 10th number will never be exactly 2. Thus, that value must always be strictly greater than 2.
  3 件のコメント
Mustafa
Mustafa 2014 年 12 月 21 日
does instructor mentioned that it must not be integer? I don't remember any necessity about it, right?
John D'Errico
John D'Errico 2014 年 12 月 21 日
編集済み: John D'Errico 2014 年 12 月 21 日
Sorry. I presumed (incorrectly) that your numbers be integers given a too fast reading of your question. Even so, it is trivial to change to generate real numbers as I show in the edit.

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

その他の回答 (2 件)

Matt J
Matt J 2014 年 12 月 21 日
編集済み: Matt J 2014 年 12 月 21 日
One way,
X=rand(10,1)*(8-1)+1 +ceil(rand(10,1))

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 21 日
X=rand(10,1)*8+1;
idx=X>2;
if nnz(idx)==0
X(randi(numel(X)))=7*rand+2;
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by