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

1 vue (au cours des 30 derniers jours)
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)?

Réponse acceptée

Star Strider
Star Strider le 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.
  2 commentaires
Karthik Ramesh Kamath
Karthik Ramesh Kamath le 18 Nov 2019
Thank you, Star Strider. This was what I was looking for!
Star Strider
Star Strider le 18 Nov 2019
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by