how to randomly vary 2 numbers?

3 views (last 30 days)
Isabel
Isabel on 5 Jul 2012
Answered: Orazio Sorgonà on 2 Apr 2022
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

Accepted Answer

John Petersen
John Petersen on 5 Jul 2012
x = 2*round(rand(30,1)) - 1;
  3 Comments
John Petersen
John Petersen on 5 Jul 2012
Edited: John Petersen on 5 Jul 2012
No it doesn't. Maybe you didn't grab the whole line?
Isabel
Isabel on 5 Jul 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!

Sign in to comment.

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 5 Jul 2012
Edited: Andrei Bobrov on 5 Jul 2012
eg
A = (rand(5) > .5) + 0;
A(~A) = -1;
or
A = 2*randi([0 1],30,1) - 1;

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

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!