How to fill a vector with just 2 elements -1 and 1, as a pseudorandom sequence?

1 view (last 30 days)
I am currently experimenting with Matlab's features, and was looking to initialize a vector with just 2 numbers -1 and 1 like a pseudorandom sequence. Tried using the following:
X = randi([-1 1], 1, N);
But the vector contained 0 along with the 2 numbers, and realized the command actually fills up the vector with elements in a given interval [min, max].
Any suggestions on how to fill the vector with just the 2 numbers (only -1 and 1)?

Accepted Answer

Star Strider
Star Strider on 18 Nov 2019
Try this:
N = 10;
xpnt = randi(2, 1, N);
X = (-1).^xpnt;
producing (in this run):
X =
-1 1 1 1 -1 -1 -1 -1 1 1
You can combine these into a single line of code if you wish. I kept them separate to demonstrate how it works.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!