MATLAB Answers

0

How can I create a random vector with at most 1 in it?

Asked by Ezz El-din Abdullah on 27 Jun 2018
Latest activity Commented on by Ezz El-din Abdullah on 27 Jun 2018
I tried to make a random vector of 0's and 1's like the code below:
v = round(rand(1,n)) % where n is the dimension of the vector
But I'd like to give it a condition to avoid the existence of 1 more than one time. Also, I want the index to be selected randomly.
For example, this:
[1 1 0 0] % where n = 4
is not accepted, but this:
[1 0 0 0]
%or
[0 1 0 0]
either of them will be accepted.
So any help please? Thanks!

  0 Comments

Sign in to comment.

1 Answer

Answer by Guillaume
on 27 Jun 2018
Edited by Guillaume
on 27 Jun 2018
 Accepted Answer

Another option:
v = randperm(n) == n
or
v = randperm(n) == 1

  2 Comments

Very neat, but this always contains one 1, whereas the title asks for "...with at most 1", which would include the possibility of zero 1's. This could be solved easily:
randperm(n)==randi(0:1)
Thanks a lot Guillaume and Stephen. Appreciate your help, both :)

Sign in to comment.