## To pick a number randomly

on 11 Sep 2012

### Andrei Bobrov (view profile)

Can some one help in picking a number from a matrix for example i have matrix of the form A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9] and i require to pick only one element randomly from the matrix but should not be the same element every time.

## Products

No products are associated with this question.

### Andrei Bobrov (view profile)

on 11 Sep 2012
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 11 Sep 2012

try this is code

```A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9];
a = unique(A);
b = a(histc(A(:),a) < 2);
idx = randperm(numel(b));
out = b(idx(1));
```

PK

### PK (view profile)

on 11 Sep 2012

its working fine can u please elaborate the working of code

on 11 Sep 2012
Edited by Rene

### Rene (view profile)

on 11 Sep 2012

The answer of andrei does not give a truly random number since he uses the unique command.

This will:

A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9];

B = round((length(A(:))-1)*rand+1);

A(B)

ps. as far as rand returns a truly random number

PK

### PK (view profile)

on 12 Sep 2012

this works fine and any method to select the numbers accordingly from first row first element to third row fifth element one after the other continuously in the manner of 1 2 3 4 5 6 6 7 5 8 12 4 5 6 9

Andrei Bobrov

### Andrei Bobrov (view profile)

on 12 Sep 2012
```A2 = reshape(A',[],1);
out = A2(randperm(numel(A),1));
```

#### Join the 15-year community celebration.

Play games and win prizes!

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