필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Regarding random generation of elements in a matrix.

조회 수: 1 (최근 30일)
Abhinav
Abhinav 2015년 2월 24일
마감: MATLAB Answer Bot 2021년 8월 20일
I have a code like this
randi([0 1],1,10)
I want it to generate random 0 and 1. But I want that it should generate at max two ones. For e.g. I should get eight zeros and two ones randomly. Please tell how to do.

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2015년 2월 24일
편집: Andrei Bobrov 2015년 2월 24일
out = zeros(1,10);
out(randperm(10,2)) = 1;
or just
out = randperm(10) > 8;

Roger Stafford
Roger Stafford 2015년 2월 24일
You stated "at max two ones", Abhinav. If you want to include the cases where there are less than two 1's, you could do it this way:
A = zeros(1,10);
if rand <= 55/56
i1 = randi(10);
A(i1) = 1;
if rand <= 45/55
i2 = randi(9);
if i2 >= i1
i2 = i2 + 1;
end
A(i2) = 1;
end
end

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by