Specific number of 1s in a 0s - 1s matrix

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2019-9-11
for it5 = 1:Num_of_Banks
a1(it5 , setdiff(1:Num_ofBanks, it5)) = randperm(Num_of_Banks-1) <= d;
end

更多回答(2 个)

Bruno Luong
Bruno Luong 2019-9-11
编辑:Bruno Luong 2019-9-11
N=10;
d=3;
[~,c] = mink(rand(N,N-1),d,2);
r = (1:N)';
c(c>=r) = c(c>=r)+1;
A = accumarray([repmat(r,[d,1]),c(:)],1,[N N])
% Check
all(diag(A)==0) % TRUE
sum(A,2) % return Nx1 vector with d

Antonio Grivas
Antonio Grivas 2019-9-11
Thank you very much for your replies ppl

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by