How to generate 0 and 1 matrix in specific condition.

26 ビュー (過去 30 日間)
Jenjen Ahmad Zaeni
Jenjen Ahmad Zaeni 2021 年 5 月 28 日
コメント済み: Jenjen Ahmad Zaeni 2021 年 5 月 29 日
Hello everyone. I want to generate a random 4x5 matrix with the elements consist of 0 and 1. But, i don't want each column to have a total amount of 1 that is less than 2. So it's more like:
A =
0 1 1 1 0
1 1 1 1 1
1 1 1 0 1
0 0 1 0 1
I'm okay if there are 2, 3, or 4 total amount of '1' element, but i don't want even a single column to have only one '1' element, or zero at all. How to make it possible? Thank you very much.

採用された回答

Matt J
Matt J 2021 年 5 月 29 日
編集済み: Matt J 2021 年 5 月 29 日
Using the attached file sortlidx,
m=4; n=15;
A=[ones(1,n);randi([0,1],m-1,n)];
[~,idx]=sortlidx(rand(m,n),1);
A=A(idx)
A = 4×15
0 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 0 1 1 1
  1 件のコメント
Jenjen Ahmad Zaeni
Jenjen Ahmad Zaeni 2021 年 5 月 29 日
Very good. It can be used for many rows and columns quickly. Thank you very much!

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2021 年 5 月 28 日
Brute force
a=randi(2,4,5)-1;
while any(sum(a)<2)
a=randi(2,4,5)-1;
end
  1 件のコメント
Jenjen Ahmad Zaeni
Jenjen Ahmad Zaeni 2021 年 5 月 28 日
Thank you, it works. But i wonder if i can do this to many more column? Lets say it's 50 and 100 column. Because when i tried to change the column to that amount, it keeps loading all the time.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by