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에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!