numbers in random positions on a zero matrix

조회 수: 2 (최근 30일)
Doobie
Doobie 2017년 5월 5일
편집: Andrei Bobrov 2017년 5월 5일
I want to generate a random matrix (let's say a 5x4 matrix) with the following properties:
  • There must be one 3, two 2s, nine 1s, eight 0s in the matrix.
  • In each row, there is at most one 3 or 2 and at most two 1s.
  • In each row, if there is a 3, then there is no 2.
  • In each row, if there is a 3, then there is one 1.
  • In each row, if there is a 2, then there are two 1s.
An example matrix:
0 0 1 1
3 1 0 0
2 1 1 0
0 1 1 2
0 1 1 0
How do I generate such a matrix? I don't even know where to begin. Any help is greatly appreciated.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 5월 5일
편집: Andrei Bobrov 2017년 5월 5일
m = 5;
n = 4;
T = [2 2 3 ones(1,9) zeros(1,8)];
out = reshape(T,m,[]);
[~,ii] = sort(rand([m,n]),2);
out = out(sub2ind([m,n],repmat((1:m)',1,n),ii));
out = out(randperm(m),:);

추가 답변 (1개)

Santhana Raj
Santhana Raj 2017년 5월 5일
Start with the function randi(4). it generates random integers. It doesnt give 0, so you can generate with a max of 4 and subtract 1 with the result.
Now with whatever number generated, check your 4 conditions. If they are all valid. place it in its position in the matrix. Repeat it for any size of matrix you want!!
  댓글 수: 1
Guillaume
Guillaume 2017년 5월 5일
randi will generate numbers in whichever range you want as long as you ask it to. To get number between 0 and 3:
randi([0 3])
No need to do some gymnastics.

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

카테고리

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