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

조회 수: 1 (최근 30일)
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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by