how to random -1 and 1?

100 visualizzazioni (ultimi 30 giorni)
Tia
Tia il 27 Lug 2013
Commentato: Stephen23 il 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

Risposta accettata

Azzi Abdelmalek
Azzi Abdelmalek il 27 Lug 2013
Modificato: Azzi Abdelmalek il 27 Lug 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
  3 Commenti
Azzi Abdelmalek
Azzi Abdelmalek il 27 Lug 2013
Exact
Tia
Tia il 27 Lug 2013
ok, thank you for your advice

Accedi per commentare.

Più risposte (3)

Andrei Bobrov
Andrei Bobrov il 27 Lug 2013
Modificato: Andrei Bobrov il 27 Lug 2013
2*randi([0 1],8)-1
or
2*(rand(8)>.5) - 1
  2 Commenti
Ahteshamul Haq
Ahteshamul Haq il 17 Apr 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 il 17 Apr 2019
Yes, the probability of getting -1 and +1 is 0.5

Accedi per commentare.


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

Francesco Sgromo
Francesco Sgromo il 8 Feb 2023
Modificato: Francesco Sgromo il 8 Feb 2023
-1^(randi(2))
  1 Commento
Stephen23
Stephen23 il 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

Accedi per commentare.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by