I want to generate a matrix which looks like this:
2 2 3 3 1 1
1 3 2 1 3 2
3 1 1 2 2 3
The specifications of the matrix is:
  1. A column contains numbers from one to the length of the column.
  2. Each number occur two times in each row
  3. Each number occur one time in each column
  4. No columns are pairwise equal more than one time.
The 3x6 matrix is generated using following code:
post = 3;
team = 6;
A = [];
stop = 0;
number_of_matrix = 0;
unique_matrix = 0;
B = zeros(post,post);
while stop == 0
for i = 1:team
A(:,i) = randsample(post,post); % Genrates a random matrix
end
number_of_matrix = number_of_matrix + 1;
for i = 1:post
B(:,i) = sum(A==i,2);
end
k = 0;
vector = zeros(1,50);
if unique(B) == 2
for m = 1:size(A,2)
for n = 1:size(A,2)
k = k + 1;
if n ~= m
vector(k) = sum(A(:,n) == A(:,m));
end
end
end
end
if unique(B) == 2
if max(vector) <= 1
stop=1;
end
end
end
disp(A)
I want to generate a 6x12 matrix, but this code is very ineffective. I have tried three different approaches, but none of them are faster that this one.
My question is: Does anyone know how to make this code more effective?

 채택된 답변

Matt Fig
Matt Fig 2012년 10월 12일
편집: Matt Fig 2012년 10월 12일

0 개 추천

Your matrix can be made with this:
perms(1:3).'
% For larger problems even ordered sets take time!!
This is significantly faster, as far as the mechanics of the code. Yet as N grows the search space grows exponentially, so if you really want a random array it will take time....
N = 4; % This is the number of rows.
P = 1:N;
P = P(ones(1,N*2),:);
S = size(P,1);
while true
K = Shuffle(P,2); % Shuffle is on the FEX
bf = 0;
for ii = 1:N
if any(sum(K==ii)~=2)
bf = 1;
break
end
end
if ~bf
break
end
end
K = K.'

댓글 수: 4

Matt he said 6x12
Matt Fig
Matt Fig 2012년 10월 12일
Yeah, I was showing how to generate the array he did show.
antlhem
antlhem 2019년 4월 28일
편집: antlhem 2019년 4월 28일
Hi, should I just change N if I want a bigger matrix? How can I use to create only binary numbers? I need a 1500x1500.
antlhem
antlhem 2019년 4월 28일
편집: antlhem 2019년 4월 28일
So far this works for me guys, if anyone needs bigger arrays:
row=1500;
col=1500;
Aunique=randi([0 1],1,col);%start
while size(Aunique,1)<row
arow=randi([0 1],1,col);
not_equal=1;
rowi=1;
while rowi<=size(Aunique,1)
if isequal(arow(1,:),Aunique(rowi,:))~=1
rowi=rowi+1;
else
not_equal=0;
break;
end
end
if not_equal==1
Aunique=cat(1,Aunique,arow);
end
end
B = unique(Aunique,'rows');%verification

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2012년 10월 12일

편집:

2019년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by