yayaya
yayaya

Reputation: 165

How do you generate a random sequence of only -1 and 1?

I want to know how to randomly generate a sequence either -1 or 1.

For example:

[1 1 -1 -1] or
[-1 1 -1 1 1 1 1 -1 ] or 
[-1 1 1 -1 1 -1 -1] are what I expect.

but [-1 0 1 -1 -1] or [2 1 -1 -1 1 1] are not what I want.

Upvotes: 3

Views: 232

Answers (2)

rayryeng
rayryeng

Reputation: 104484

There are several ways to do this.

Method #1 - Selecting from a small array

You can create a small array that consist of [-1 1], then create random integers that contain either 1 or 2 and index into this sequence:

N = 10; %// Number of values in the array

%// Generate random indices
ind = randi(2, N, 1);

%// Create small array
arr = [-1; 1];

%// Get final array
out = arr(ind);

Method #2 - Generate values from a uniform random distribution and threshold

You can also generate random uniformly distributed floating point values, and anything larger than 0.5, you can set to 1, and anything less you can set to -1.

N = 10; %// Number of values in the array

%// Generate randomly distributed floating point values
out = rand(N, 1);

%// Find those locations that are >= 0.5
ind = out >= 0.5;

%// Set the right locations to +1/-1
out(ind) = 1;
out(~ind) = -1;

Method #3 - Use trigonometry

You can use the fact that cos(n*pi) can either give 1 or -1, depending on what value that n is as long as n is an integer. Odd values produce -1 while even values produce 1. As such, you can generate a bunch of random integers that are either 1 or 2, and calculate cos(n*pi):

N = 10; %// Number of values in the array

%// Generate random integers
ind = randi(2, N, 1); 

%// Compute sequence via trigonometry
out = cos(ind*pi);

Upvotes: 2

gregswiss
gregswiss

Reputation: 1456

One liner for N elements:

2*randi(2, 1, N) - 3

or maybe clearer

(-1).^randi(2, 1, N)

Upvotes: 3

Related Questions