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

 Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 27 Jul. 2013
Bearbeitet: Azzi Abdelmalek am 27 Jul. 2013

0 Stimmen

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 Kommentare

kjetil87
kjetil87 am 27 Jul. 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 am 27 Jul. 2013
Exact
Tia
Tia am 27 Jul. 2013
ok, thank you for your advice

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (3)

Andrei Bobrov
Andrei Bobrov am 27 Jul. 2013
Bearbeitet: Andrei Bobrov am 27 Jul. 2013

4 Stimmen

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

2 Kommentare

Ahteshamul Haq
Ahteshamul Haq am 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 am 17 Apr. 2019
Yes, the probability of getting -1 and +1 is 0.5

Melden Sie sich an, um zu kommentieren.

Mendi
Mendi am 19 Aug. 2020

0 Stimmen

randsample([-1, 1],8,true)
Francesco Sgromo
Francesco Sgromo am 8 Feb. 2023
Bearbeitet: Francesco Sgromo am 8 Feb. 2023

0 Stimmen

-1^(randi(2))

1 Kommentar

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Random Number Generation finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by