what is the single command?????????

I want to create matrix size is 100*12. Each row contain only 5 zeros other elements are 1. for ex
A=[1 1 1 0 0 1 1 0 0 0 1 1 ;
0 0 1 1 0 0 1 1 0 1 1 1;]
Note: Nobody row is repeated

2 件のコメント

Stephen23
Stephen23 2018 年 8 月 17 日
編集済み: Stephen23 2018 年 8 月 17 日
[zeros(100,5),ones(100,7)]
VIJAY
VIJAY 2018 年 8 月 17 日
thank you guy but rows are repeated.........

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

 採用された回答

Stephen23
Stephen23 2018 年 8 月 17 日
編集済み: Stephen23 2018 年 8 月 17 日

2 投票

R = 100; % rows
C = 12; % columns
N = 5; % number of 1's.
cmb = nchoosek(1:C,N); % all unique column combinations.
idx = randperm(size(cmb,1)); % indices to randomize combinations.
idc = cmb(idx(1:R),:); % (col index) pick first 100 random combinations.
idr = ndgrid(1:R,1:N); % (row index).
mat = ones(R,C); % preallocate output matrix.
mat(sub2ind([R,C],idr,idc)) = 0
Check:
>> all(sum(mat,2)==7) % all rows sum to seven.
ans = 1
>> all(ismember(mat(:),0:1)) % only 0's and 1's.
ans = 1
>> size(unique(mat,'rows')) % all rows are unique.
ans =
100 12

4 件のコメント

VIJAY
VIJAY 2018 年 8 月 17 日
Your one of the row of your output as follow 1 1 0 0 0 0 1 0 0 1 1 0
I need only 5 zeros in a row others are 1 but here your code work for only 5 ones in a row others are 0
i need 0 instead of 1 in your code.........
Stephen23
Stephen23 2018 年 8 月 17 日
編集済み: Stephen23 2018 年 8 月 17 日
@VIJAY: just change the zeros to ones, and the last line allocates 0. See my edited answer.
VIJAY
VIJAY 2018 年 8 月 17 日
thank you .......
Stephen23
Stephen23 2018 年 8 月 17 日
@VIJAY: I hope that it helps. Remember to accept the answer. Accepting my answer is the easiest way to thank me.

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

その他の回答 (1 件)

Rik
Rik 2018 年 8 月 17 日

2 投票

First generate all combinations, and then select 100 from them:
total_row_length=12;
number_of_zeros=5;
selected_number_of_rows=100;
v=1:total_row_length;
col_positions = nchoosek(v,number_of_zeros);
row_positions=repmat((1:size(col_positions,1))',1,size(col_positions,2));
out=ones(size(col_positions,1),total_row_length);
inds=sub2ind(size(out),row_positions,col_positions);
out(inds)=0;
%select a random sample from all possible rows
selected_rows=randperm(size(out,1),selected_number_of_rows);
result=out(selected_rows,:);

2 件のコメント

Stephen23
Stephen23 2018 年 8 月 17 日
編集済み: Stephen23 2018 年 8 月 17 日
@Star Strider: can you please give explanations for your votes, rather than just disappearing without comment. I am interested to know what you found in Rik Wisselink's answer, that you felt was missing in mine (they are almost identical). Many thanks!
VIJAY
VIJAY 2018 年 8 月 20 日
Thank you for answering..........

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

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2018 年 8 月 17 日

コメント済み:

2018 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by