how to randomly vary 2 numbers?

9 vues (au cours des 30 derniers jours)
Isabel
Isabel le 5 Juil 2012
Hi! I want to generate a column of 30 randomly varying -1s and 1s. How can I do that? I was trying randi([-1:2:1],30,1) but that gives me zeros too and I don't want zeros, only -1 and 1. Thanks

Réponse acceptée

John Petersen
John Petersen le 5 Juil 2012
x = 2*round(rand(30,1)) - 1;
  3 commentaires
John Petersen
John Petersen le 5 Juil 2012
Modifié(e) : John Petersen le 5 Juil 2012
No it doesn't. Maybe you didn't grab the whole line?
Isabel
Isabel le 5 Juil 2012
Sorry, it does work, my bad. I think I din't copy the whole formula or something. Thank you very much for your answer!

Connectez-vous pour commenter.

Plus de réponses (2)

Andrei Bobrov
Andrei Bobrov le 5 Juil 2012
Modifié(e) : Andrei Bobrov le 5 Juil 2012
eg
A = (rand(5) > .5) + 0;
A(~A) = -1;
or
A = 2*randi([0 1],30,1) - 1;
  1 commentaire
Isabel
Isabel le 5 Juil 2012
Thanks! this works well

Connectez-vous pour commenter.


Orazio Sorgonà
Orazio Sorgonà le 2 Avr 2022
I use
A = -1^(randi([1,2]));

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by