Random number vector with only two values

5 ビュー (過去 30 日間)
Sania Gul
Sania Gul 2024 年 9 月 23 日
コメント済み: Sania Gul 2024 年 9 月 23 日
I want to generate 10 random numbers, but the value of these must be either 0 or pi=3.14. I have tried with randperm, randi, rand etc. but neither worked. Plz help me to resolve it.

採用された回答

Stephen23
Stephen23 2024 年 9 月 23 日
編集済み: Stephen23 2024 年 9 月 23 日
Indexing is a basic MATLAB superpower. You can easily use indexing to select from a vector of any values:
V = [0,pi];
W = V(randi(numel(V),1,10))
W = 1×10
0 0 0 0 3.1416 0 0 3.1416 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Multiplication also works for this special case with only two values, one of which is zero:
W = pi * randi([0,1],1,10)
W = 1×10
3.1416 3.1416 0 0 3.1416 3.1416 3.1416 0 0 3.1416
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 件のコメント
Sania Gul
Sania Gul 2024 年 9 月 23 日
Tnx a lot Stephen :-).

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

その他の回答 (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