how to random -1 and 1?

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

 Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 27 de Jul. de 2013
Editada: Azzi Abdelmalek el 27 de Jul. de 2013

0 votos

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 comentarios

kjetil87
kjetil87 el 27 de Jul. de 2013
you should be carefull about method 2 if you want it to be actually random, here there is a 2/3 chance of -1 , and 1/3 of +1.
Azzi Abdelmalek
Azzi Abdelmalek el 27 de Jul. de 2013
Exact
Tia
Tia el 27 de Jul. de 2013
ok, thank you for your advice

Iniciar sesión para comentar.

Más respuestas (3)

Andrei Bobrov
Andrei Bobrov el 27 de Jul. de 2013
Editada: Andrei Bobrov el 27 de Jul. de 2013

4 votos

2*randi([0 1],8)-1
or
2*(rand(8)>.5) - 1

2 comentarios

Ahteshamul Haq
Ahteshamul Haq el 17 de Abr. de 2019
Is the probabilty of getting -1 and +1 is 0.5. If not, kindly suggest a way to get it.
James Tursa
James Tursa el 17 de Abr. de 2019
Yes, the probability of getting -1 and +1 is 0.5

Iniciar sesión para comentar.

Francesco Sgromo
Francesco Sgromo el 8 de Feb. de 2023
Editada: Francesco Sgromo el 8 de Feb. de 2023

0 votos

-1^(randi(2))

1 comentario

(-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

Iniciar sesión para comentar.

Categorías

Más información sobre Random Number Generation en Centro de ayuda y File Exchange.

Preguntada:

Tia
el 27 de Jul. de 2013

Comentada:

el 8 de Feb. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by