MATLAB Answers

## how to random -1 and 1?

Asked by Tia

### Tia (view profile)

on 27 Jul 2013
Accepted Answer by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

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

#### 0 Comments

Log in to comment.

## 2 Answers

### Azzi Abdelmalek (view profile)

Answer by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 27 Jul 2013
Edited by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 27 Jul 2013
Accepted Answer

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

kjetil87

### kjetil87 (view profile)

on 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

on 27 Jul 2013

Exact

Tia

### Tia (view profile)

on 27 Jul 2013

ok, thank you for your advice

Log in to comment.

### Andrei Bobrov (view profile)

Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

on 27 Jul 2013
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 27 Jul 2013

```2*randi([0 1],8)-1
```

or

```2*(rand(8)>.5) - 1
```

#### 0 Comments

Log in to comment.

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

### MATLAB Academy

New to MATLAB?

Learn MATLAB today!