Create matrix (30 x 12) with numbers from 1 to 12 without repetition without any repetitions of following numbers for each row
1 view (last 30 days)
Show older comments
JA
on 4 Nov 2019
Answered: JESUS DAVID ARIZA ROYETH
on 4 Nov 2019
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!
Accepted Answer
JESUS DAVID ARIZA ROYETH
on 4 Nov 2019
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)
0 Comments
More Answers (2)
Matt J
on 4 Nov 2019
Edited: Matt J
on 4 Nov 2019
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,:)
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!