Home > front end >  Generating a random binary matrix with a constraint
Generating a random binary matrix with a constraint

Time:01-04

We are using MATLAB and we would like to generate a binary matrix, say x(i,j,k), where for every i, this condition is satisfied sum_{j} \ sum_{k} x_{ijk} = 1. Can anyone please help?

CodePudding user response:

Generate random subscripts for j and k and use sub2ind to convert subscripts to indexes.

x = false(ni, nj, nk);  
subi = 1:ni;
subj = randi(nj, 1, ni);
subk = randi(nk, 1, ni);
ind = sub2ind([ni, nj, nk], subi, subj, subk);
x(ind) = true;

To confirm the constraint you can use:

all(sum(sum(x, 3), 2) == 1)
  • Related