Can anybody help me create a simple pseudo-random sequence of +-1 integers with length 1000 using Matlab?
I.e. a sequence such as
-1 -1 1 1 -1 -1 1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1
I tried using this code below but this is the RANGE -1 to 1, which includes 0 values. I only want -1 and 1. Thanks
x = randi([-1 1],1000,1);
You can try generating a random sequence of floating point numbers from [0,1]
and any values less than 0.5 set to -1, and anything larger set to 1:
x = rand(1000,1);
ind = x >= 0.5;
x(ind) = 1;
x(~ind) = -1;
Another suggestion I have is to use the sign
function combined with randn
so that we can generate both positive and negative numbers. sign
generates values that are either -1, 0, 1 depending on the sign of the input. If the input is negative, the output is -1, +1 when positive and 0 when 0. You could do an additional check where any values that are output to 0, set them to -1 or 1:
x = sign(randn(1000,1));
x(x == 0) = 1;
One more (inspired by Luis Mendo) would be to have a vector of [-1,1]
and use randi
to generate a sequence of either 1 or 2, then use this and sample into this vector:
vec = [-1 1];
x = vec(randi(numel(vec), 1000, 1));
This code can be extended where vec
can be anything you want, and we can sample from any element in vec
to produce a random sequence of values (observation made by Luis Mendo. Thanks!).