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

1 Ansicht (letzte 30 Tage)
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?

Akzeptierte Antwort

Michele Facchinelli
Michele Facchinelli am 12 Okt. 2019
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:

Weitere Antworten (1)

Stephen23
Stephen23 am 12 Okt. 2019
>> 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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by