Create logical matrix with a specific row and column sums - MATLAB Cody - MATLAB Central

Problem 885. Create logical matrix with a specific row and column sums

Difficulty:Rate

Given two numbers n and s, build an n-by-n logical matrix (of only zeros and ones), such that both the row sums and the column sums are all equal to s. Additionally, the main diagonal must be all zeros.

You can assume that: 0 < s < n

 

Example:

Take n=10 and s=3, here is a possible solution

M =
     0     1     0     0     1     1     0     0     0     0
     0     0     1     0     1     1     0     0     0     0
     0     0     0     0     1     1     0     0     1     0
     0     0     0     0     0     0     1     1     0     1
     1     0     0     0     0     0     1     0     1     0
     0     1     1     0     0     0     0     1     0     0
     1     0     0     1     0     0     0     0     0     1
     0     0     0     1     0     0     0     0     1     1
     1     1     0     0     0     0     0     1     0     0
     0     0     1     1     0     0     1     0     0     0

Note that the following conditions are all true:

all(sum(M,1)==3)     % column sums equal to s
all(sum(M,2)==3)     % row sums equal to s
all(diag(M)==0)      % zeros on the diagonal
islogical(M)         % logical matrix
ndims(M)==2          % 2D matrix
all(size(M)==n)      % square matrix

 

Unscored bonus:

Visualize the result as a graph where M represents the adjacency matrix:

% circular layout
t = linspace(0, 2*pi, n+1)';
xy = [cos(t(1:end-1)) sin(t(1:end-1))];
subplot(121), spy(M)
subplot(122), gplot(M, xy, '*-'), axis image

Solution Stats

31.38% Correct | 68.62% Incorrect
Last Solution submitted on Nov 11, 2025

Problem Comments

Solution Comments

Show comments
Join Cody Contest 2025 — Have Fun and Win Prizes!
...
We’re excited to invite you to Cody Contest 2025! 🎉 Pick a team,...

Problem Recent Solvers333

Suggested Problems

Problem Tags

Community Treasure Hunt

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

Start Hunting!