Can anyone help me to generate a matrix of 0's and 1's randomly in which each contains only one 1 like [ 0 1 0 0 0; 1 0 0 0 0; 0 0 0 1 0].
1 回表示 (過去 30 日間)
古いコメントを表示
for example
[0 1 0 0 0; 1 0 0 0 0; 0 0 0 1 0]
0 件のコメント
採用された回答
Andrei Bobrov
2016 年 6 月 17 日
編集済み: Andrei Bobrov
2016 年 6 月 17 日
[~,ii] = sort(rand(3,5),2)
out = ii == 1
or
out = zeros(3,5)
[m,n] = size(out);
out(sub2ind([m,n],1:m,randperm(n,m))) = 1
3 件のコメント
Shameer Parmar
2016 年 6 月 17 日
@Andrei: your first solution producing sometime repeated values..like..
out =
1 0 0 0 0
1 0 0 0 0
0 0 1 0 0
and in second solution, what is m and n ?
その他の回答 (2 件)
Jos (10584)
2016 年 6 月 17 日
One 1 in each ... what? rows, columns, or both?
Given your examples and comment I assume both, so here is a simple one-liner. NR and NC are the number of rows and columns, respectively. Note that NC should be larger or equal to NR
A = full(sparse(1:NR, randperm(NC,NR), 1, NR, NC))
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!