MATLAB: Specific number of 1s in a 0s – 1s matrix

digraphsmatrixNetworkrandom

I want to create a NxN matrix or random 1s and 0s so that in every row can appear 2 – two 1s and N-2 0s or k-1 same in every row
The problem is that I cannot have a 1 in its diagonial [bank i cannot lend or borrow from bank i]
What I have till now is
% d=3; % minimum ones per row (it creates more than 2 !!! )
d=randi([2 Num_of_Banks] , 1);
% minimum ones per row (it puts 1s in diag which is multiplied with 0 so I finally have 1 one so I must use a return or break I suppose)
a1 = zeros(Num_of_Banks, Num_of_Banks);
for it5 = 1:Num_of_Banks
a1(it5 , :) = randperm(Num_of_Banks) <= d;
end
a1;
Initial_Network = a1 .* (ones(Num_of_Banks) - eye(Num_of_Banks))
I have searched but I found nothing although I know that this must have been answered before
If someone can help

Best Answer

for it5 = 1:Num_of_Banks
a1(it5 , setdiff(1:Num_ofBanks, it5)) = randperm(Num_of_Banks-1) <= d;
end