how to random -1 and 1?

62 次查看(过去 30 天)
Tia
Tia 2013-7-27
评论: Stephen23 2023-2-8
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
Azzi Abdelmalek 2013-7-27
编辑:Azzi Abdelmalek 2013-7-27
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
  3 个评论
Tia
Tia 2013-7-27
ok, thank you for your advice

请先登录,再进行评论。

更多回答(3 个)

Andrei Bobrov
Andrei Bobrov 2013-7-27
编辑:Andrei Bobrov 2013-7-27
2*randi([0 1],8)-1
or
2*(rand(8)>.5) - 1
  2 个评论
Ahteshamul Haq
Ahteshamul Haq 2019-4-17
Is the probabilty of getting -1 and +1 is 0.5. If not, kindly suggest a way to get it.
James Tursa
James Tursa 2019-4-17
Yes, the probability of getting -1 and +1 is 0.5

请先登录,再进行评论。


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

Francesco Sgromo
Francesco Sgromo 2023-2-8
编辑:Francesco Sgromo 2023-2-8
-1^(randi(2))
  1 个评论
Stephen23
Stephen23 2023-2-8
(-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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by