Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
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 commentaire
Stephen23
Stephen23 le 12 Oct 2019
Modifié(e) : Stephen23 le 12 Oct 2019
"How can I use an if-else statement..."
Using if-else would more complex than writing vectorized code.

Connectez-vous pour commenter.

Réponse acceptée

Michele Facchinelli
Michele Facchinelli le 12 Oct 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:

Plus de réponses (1)

Stephen23
Stephen23 le 12 Oct 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

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by