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

조회 수: 1 (최근 30일)
Ezz El-din Abdullah
Ezz El-din Abdullah 2018년 6월 27일
댓글: Ezz El-din Abdullah 2018년 6월 27일
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!

채택된 답변

Guillaume
Guillaume 2018년 6월 27일
편집: Guillaume 2018년 6월 27일
Another option:
v = randperm(n) == n
or
v = randperm(n) == 1
  댓글 수: 2
Stephen23
Stephen23 2018년 6월 27일
편집: Stephen23 2018년 6월 27일
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)
Ezz El-din Abdullah
Ezz El-din Abdullah 2018년 6월 27일
Thanks a lot Guillaume and Stephen. Appreciate your help, both :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by