Create matrix (30 x 12) with numbers from 1 to 12 without repetition without any repetitions of following numbers for each row

조회 수: 5 (최근 30일)
Hi all,
I want to create a matrix (30 rows, 12 columns) with numbers from 1 to 12. Each row should be as unique as possible, so that two numbers are barely following each other.
For example:
11 3 8 9 12 4 10 5 1 7 6 2
6 7 5 1 4 9 12 3 8 2 11 10
In this case of only 2 rows 8 follows 3 and 12 follows 9. This is what I want to avoid.
Can anyone help me out?
Thanks in advance!

채택된 답변

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 11월 4일
here the solution:
A=randperm(12);
iterac=500;
for k=1:30-1
it=0;
while true
it=it+1;
b=randperm(12);
c2=[diff(b); b(1:end-1) .* b(2:end)];
cd=0;
for j=1:size(A,1)
c=[diff(A(j,:)); A(j,1:end-1) .* A(j,2:end)];
if size(intersect(c',c2','rows'),1)<=1 || (size(intersect(c',c2','rows'),1)<=2 && it>iterac)
cd=cd+1;
end
end
if cd==size(A,1)
A(end+1,:)=b;
break
end
end
end
disp(A)

추가 답변 (2개)

Bhaskar R
Bhaskar R 2019년 11월 4일
Uniformly distributed pseudorandom integers using the command
randi
may produce as you require
mat = randi([1, 12], 30, 12)

Matt J
Matt J 2019년 11월 4일
편집: Matt J 2019년 11월 4일
Note that there are only
>> nchoosek(12,2)*2
ans =
132
distinct subsequences of length 2 that can be drawn from the numbers 1-12, and a 30x12 matrix contains 330 such sequences. So, it is inevitable that the result will contain several hundred repetitions.
However, you might wish to consider the following as a way to diminish the similarities between rows.
m=12;
n=30;
k=n*100;
[~,P]=sort(rand(k,12),2);
D=pdist2(P,P);
[~,I]=maxk(max(D,[],2),n);
I=nan(1,n);
I(1)=1;
for k=1:n-1
i=I(k);
[~,j]=max(D(i,:),[],2);
D(i,:)=nan; D(:,i)=nan;
I(k+1)=j;
end
result=P(I,:)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by