Specific number of 1s in a 0s - 1s matrix
2 views (last 30 days)
Show older comments
Antonio Grivas
on 11 Sep 2019
Edited: Bruno Luong
on 11 Sep 2019
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
0 Comments
Accepted Answer
Walter Roberson
on 11 Sep 2019
for it5 = 1:Num_of_Banks
a1(it5 , setdiff(1:Num_ofBanks, it5)) = randperm(Num_of_Banks-1) <= d;
end
0 Comments
More Answers (2)
Bruno Luong
on 11 Sep 2019
Edited: Bruno Luong
on 11 Sep 2019
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
0 Comments
See Also
Categories
Find more on Sparse Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!