How can I create an input row only excisting randomly only out of -1 and +1?
1 view (last 30 days)
Show older comments
Chris Ron de
on 12 Oct 2019
Answered: Michele Facchinelli
on 12 Oct 2019
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 Comment
Accepted Answer
Michele Facchinelli
on 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:
0 Comments
More Answers (1)
Stephen23
on 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
0 Comments
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!