Create a row Matrix

조회 수: 22 (최근 30일)
Konstantinos
Konstantinos 2015년 1월 12일
댓글: John D'Errico 2015년 1월 13일
I want to create a row matrix of 20 elements (1x20), which consists of 1s and 0s. 1s are generated with rate:r and 0s are generated with rate:(1-r), where r could be any random number between 0 and 1 ( 0<r<1 ).
Any help could be useful. Thanks in advance!

채택된 답변

Star Strider
Star Strider 2015년 1월 12일
편집: Star Strider 2015년 1월 12일
This is one option:
r = 0.5;
idx = randperm(20, ceil(r*20));
rv = zeros(1,20);
rv(idx) = 1;
The logic is relatively straightforward: ‘idx’ uses rendperm to generate a matrix of index positions, then generates ‘rv’ and uses ‘idx’ to determine the r*20 values that are set to 1.
With r = 0.5, this yields:
rv =
Columns 1 through 17
0 1 0 0 1 0 0 1 1 1 1 0 1 0 0 1 1
Columns 18 through 20
1 0 0
  댓글 수: 4
Konstantinos
Konstantinos 2015년 1월 12일
Thanks a lot guys for your time. I really appreciate your help!
Star Strider
Star Strider 2015년 1월 12일
Our pleasure!

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

추가 답변 (1개)

John D'Errico
John D'Errico 2015년 1월 12일
편집: John D'Errico 2015년 1월 12일
Well, since a test returns a 0 or 1 (i.e., true or false) what is the probability that each element of a set of random samples, taken by the call rand(1,20), is greater than r? What is the probability that they are less than r?
x = (rand(1,20) >= r);
  댓글 수: 10
Star Strider
Star Strider 2015년 1월 13일
@John — That seems to be the crux of the issue. I voted for your answer because in Konstantinos’ original Question, it was not possible to determine what was desired. By my reading, both your Answer and mine are equally valid.
John D'Errico
John D'Errico 2015년 1월 13일
Star - Oh, I don't dispute that you may arguably have a valid answer of the question. Questions are frequently slightly ambiguous, so they can often be read many ways. My patience today is clearly stressed by probabilistically meaningless statements like this:
"if r = 0.37, then the number of ones I want is: N1 = ceil(r*20)=8 1s and No=(1 - N1)=12 0s"

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

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by