Randomized array with limits
이전 댓글 표시
I am having a huge problem in generating a randomized array with 3 lines and for collumns that has to be of this type 2 1 3 1
3 2 1 2
1 3 2 3;
basicly the limits are in each column their has to exist at least this a number 1, 2 and 3, because it has 4 columns one of the numbers will always repeat in each line obviously, this is what i have done so far but can't seem to do better than this.
mp=[];
mp1=randperm(3)';
mp2=randperm(3)';
mp3=randperm(3)';
mp=[mp mp1 mp2 mp3]
댓글 수: 2
Walter Roberson
2020년 12월 12일
If you used the same randperm for the initial mp then you would get 4 columns.
ricardo Alcobia
2020년 12월 12일
답변 (2개)
Rik
2020년 12월 12일
A=1:3;A(4)=randi(3);
mp=A(randperm(end))
Image Analyst
2020년 12월 12일
Try this:
% Initialize.
rows = 3;
columns = 4;
% Each row of A starts out like [1, 2, 3, rowNumber] to follow the poster's example/directions.
% So first row will have 2 1s, second row will have 2 2s, and third row will have 2 3s.
A= [repmat(1:columns-1, [rows, 1]), (1:rows)']
mp = A;
% Go down each row, scrambling the columns
for row = 1 : size(A, 1)
order = randperm(size(A, 2));
mp(row, :) = A(row, order);
end
mp
You'll see
A =
1 2 3 1
1 2 3 2
1 2 3 3
mp =
1 2 3 1
2 3 1 2
1 3 3 2
as required.
댓글 수: 3
ricardo Alcobia
2020년 12월 12일
Image Analyst
2020년 12월 12일
편집: Image Analyst
2020년 12월 12일
I guess I misinterpreted what you said and your example. Try this code (much shorter and simpler than yours):
% Initialize.
rows = 3;
columns = 4;
% Each column of A starts out like [1; 2; 3]. Each row will be the row number.
% then we'll scramble the order of the rows, column-by-column.
mp = [repmat((1:rows)', [1, columns])]
% Go across each column, scrambling the rows in each column.
for col = 1 : columns
order = randperm(rows);
mp(:, col) = mp(order, col);
end
mp
You'll get, for example:
mp =
1 1 2 2
3 3 1 3
2 2 3 1
Looks like you maybe want a "Latin Rectangle". Have you ever heard of that?
ricardo Alcobia
2020년 12월 12일
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!