# how to random -1 and 1?

149 views (last 30 days)
Tia on 27 Jul 2013
Commented: Stephen23 on 8 Feb 2023
m=round(2*rand(8)-1)
the output:
m =
1 0 0 1 0 0 0 -1
1 1 0 0 1 1 0 -1
0 1 -1 0 0 0 1 1
1 0 0 1 0 0 1 0
0 0 -1 1 1 -1 1 1
-1 -1 -1 1 -1 0 0 -1
-1 -1 1 -1 0 -1 1 0
0 -1 0 1 1 0 0 0
but i don't want zero's output. can anyone help me clear this? thanks

Azzi Abdelmalek on 27 Jul 2013
Edited: Azzi Abdelmalek on 27 Jul 2013
m=randi(2,8)-1
m(~m)=-1
%or
m=randi([-1 ,1],8)
m(~m)=-1
%or
m=fix(rand(8)+0.5)
m(~m)=-1
Tia on 27 Jul 2013

Andrei Bobrov on 27 Jul 2013
Edited: Andrei Bobrov on 27 Jul 2013
2*randi([0 1],8)-1
or
2*(rand(8)>.5) - 1
##### 2 CommentsShow 1 older commentHide 1 older comment
James Tursa on 17 Apr 2019
Yes, the probability of getting -1 and +1 is 0.5

Mendi on 19 Aug 2020
randsample([-1, 1],8,true)

Francesco Sgromo on 8 Feb 2023
Edited: Francesco Sgromo on 8 Feb 2023
-1^(randi(2))
Stephen23 on 8 Feb 2023
(-1).^randi(2,8,8)
ans = 8×8
1 1 1 -1 -1 1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 1 -1 1 -1 1 1 -1 -1 -1 1 -1 1 1 -1 -1 -1 -1 -1 1 1 -1 -1 1 -1 -1 -1 1 1 1 -1 1 -1 1 1 1 -1 -1 -1 -1 1