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
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
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
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
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
>
  1 个评论
Darek Myszk
Darek Myszk 2018-10-26
Hi. Thanks for reply.
I changed the task, and now I need only one, square matrix (without eye matrix). Sum of each row and column must be equal to the given condition. (limit of 1's < matrix size)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by