Create a matrix with unique coloms and rows

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?

 Accepted Answer

Matt Fig
Matt Fig on 12 Oct 2012
Edited: Matt Fig on 12 Oct 2012
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 Comments

Yeah, I was showing how to generate the array he did show.
antlhem
antlhem on 28 Apr 2019
Edited: antlhem on 28 Apr 2019
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.
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

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!