Effacer les filtres
Effacer les filtres

Create random regular matrix (Matlab)

8 vues (au cours des 30 derniers jours)
high speed
high speed le 29 Oct 2021
Commenté : John D'Errico le 30 Oct 2021
Dear members,
I have the program below, that create a random regular (equal number of ones in each row and column) matrix.
But it works just with small numbers of M*N (dimensions of the matrix). When I try to augment the dimensions for example for 216*432, it runs without stopping.
Can anyone help me to solve the problem please.
clear;clc;
N=12; % Number of columns
M=6; % Number of rows
n=4; % Number of ones in each column
m=2; % Number of ones in each row
a=[ones(1,n),zeros(1,N-n)];
b=a;
c=zeros(M,N);
while ~all(b==m)
for k=1:M
c(k,:)=a(randperm(N));
end
b=sum(c);
end
spy(c)
  1 commentaire
Jan
Jan le 30 Oct 2021
Your code replies a matrix with n ones in each row and m ones in each column, not vice- versa.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 30 Oct 2021
Modifié(e) : Jan le 30 Oct 2021
Having m ones in each column and n ones in each row works only, if the the resulting matrix has the size [a*m, a*n].
A constructive approach is more efficient then permuting randomly and checking, if the output meets the conditions. Remember that the number of permutations grows massively with the number of inputs.
Start with a block diagonal matrix and permute the rows and columns randomly:
M = 216; % Number of rows
N = 432; % Number of columns
m = 2; % Number of ones in each row
n = 4; % Number of ones in each column
a = M / m; % Must be N / n
C = kron(eye(a), ones(m, n)); % Block diagonal matrix
C(randperm(M), :) = C;
C(:, randperm(N)) = C;
all(sum(C, 1) == m) && ... % number of ones per column
all(sum(C, 2) == n) % number of ones per row
ans = logical
1
  2 commentaires
high speed
high speed le 30 Oct 2021
@Jan Thank you so much. It works
John D'Errico
John D'Errico le 30 Oct 2021
Good answer by Jan. An important point to remember is that very frequently, when you know the number of elements you want, but you just don't know the location, a great idea is to start with a non-random solution that satisfies your "goal" and then permute it randomly.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by