How can I create an input row only excisting randomly only out of -1 and +1?

1 回表示 (過去 30 日間)
Chris Ron de
Chris Ron de 2019 年 10 月 12 日
回答済み: Michele Facchinelli 2019 年 10 月 12 日
As an input for an equation or a function I want to make a row of inputvalues. The only value that they can have is -1 and +1. They have to be in random order. I tried to make uniform distribution between 0 and 1. I thought that it had to be possible to change the values which are > 0.5 to 1 and al the other values to -1.
How can I use an if-else statement in a vector to get this done or can it be done in an other way?
  1 件のコメント
Stephen23
Stephen23 2019 年 10 月 12 日
編集済み: Stephen23 2019 年 10 月 12 日
"How can I use an if-else statement..."
Using if-else would more complex than writing vectorized code.

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

採用された回答

Michele Facchinelli
Michele Facchinelli 2019 年 10 月 12 日
You can use the function randi to generate psuedo-random integers between 1 and 2, then replace the 2's with -1's:
x = randi( 2, 1, 100 );
x( x == 2 ) = -1;
x
The first input to randi is the value of the largest integer (where the smallest integer is implicitly set to 1), and the two consecutive inputs represent the size of the output matrix, i.e., 1 x 100.
The second lne first looks for all the values of x that equal 2 (x == 2), then assigns two these the value -1. The first operations is called logical indexing, whereas the second one is implicit expansion.
You can find more information on randi here:
and on implicit expansion here:

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 10 月 12 日
>> V = [-1,1];
>> X = randi(2,1,23);
>> V(X)
ans =
-1 -1 1 1 1 -1 -1 -1 1 -1 1 -1 1 1 1 -1 1 1 -1 -1 -1 -1 -1

カテゴリ

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