How can produce this matrix?
Show older comments
I want to produce a m×n matrix for example like this: x=[1 1 1 0 1 0 1 1; 0 0 0 1 0 1 0 0] This matrix can give 0 or 1 for its elements. This 0 and 1 elements must be randomly distributed so that sum of each column is equal to one. I have a value like "k" that sum of the fisrt row can be equal or less than k. In defining the above matrix I also want to consider the following conditions: if the sum of the first row is less than k the all elements in the first row must be consider to 1 and all elements in the other rows must be zero. Otherwise, if the sum of the first row is equal to k the first row elements can be 0 or 1 but remind that the sum of each column must be 1.
5 Comments
Dyuman Joshi
on 6 Dec 2023
What if the sum of the first row is greater than k?
S AsZ
on 6 Dec 2023
Dyuman Joshi
on 6 Dec 2023
But what if it is? What should be the output then?
Should the function generate a new matrix in that case?
S AsZ
on 6 Dec 2023
S AsZ
on 6 Dec 2023
Accepted Answer
More Answers (1)
Walter Roberson
on 6 Dec 2023
Edited: Walter Roberson
on 6 Dec 2023
For the sum of each column to be 1, and the elements are each 0 or 1, then it follows that for every column, there must be exactly 1 row that is set to 1. You can use randi() to select the rows.
M = 5; N = 4;
matrix = zeros(M, N);
matrix(sub2ind([M,N], randi(M, N, 1), (1:N).' )) = 1;
matrix
Categories
Find more on Logical 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!