Specified number of ones in the matrix
1 次查看(过去 30 天)
显示 更早的评论
Hi. I have a problem. In brief. for example: I generate a matrix 8x4 filled 0/1. First 4 column have in random places 0/1, last four column is unit matrix.
0 1 0 0 1 0 0 0
1 1 0 1 0 1 0 0
1 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1
next, I set the limit of ones in row; and adds, subtracts ones to get the compatibility as in the picture below.

Thank you for your help.
1 个评论
the cyclist
2018-10-22
You haven't really asked a question here. I suppose your question is "How do I do this?", but I do not fully understand what "this" is.
You haven't given us enough details. How is the first part filled in? Is it completely random 0/1? Or are there always the correct number of 1's, and they just need to be rearranged? Is there some rule about moving 1's in the first column first, etc? Please specify the details.
My general advice would be to write the steps of the algorithm first, just in words. Then in pseudocode. Then you have a chance of writing the algorithm in MATLAB code.
You cannot program rules that you do not fully understand (and you have not helped us understand).
回答(2 个)
Akira Agata
2018-10-24
If your goal is to obtain the final 4-by-8 matrix, how about the following?
A = [zeros(4), eye(4)];
for kk = 1:4
A(kk,randperm(4,2))=1;
end
3 个评论
Akira Agata
2018-10-28
OK. Then, how about this? This code generates 4-by-4 binary matrix containing two 1s for each row and column.
A = eye(4)+circshift(eye(4),1);
A = A(randperm(4),randperm(4));
Bruno Luong
2018-10-24
[~,j]=maxk(rand(4),2,1);
A = [accumarray([ceil((1:8)'/2),j(:)],1,[4 4]) eye(4)]
ans =
1 1 0 0 1 0 0 0
0 1 1 0 0 1 0 0
1 1 0 0 0 0 1 0
0 1 0 1 0 0 0 1
>
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!