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].

3 visualizaciones (últimos 30 días)
for example
[0 1 0 0 0; 1 0 0 0 0; 0 0 0 1 0]

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 17 de Jun. de 2016
Editada: Andrei Bobrov el 17 de Jun. de 2016
[~,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 comentarios
Shameer Parmar
Shameer Parmar el 17 de Jun. de 2016
@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 ?

Iniciar sesión para comentar.

Más respuestas (2)

Shameer Parmar
Shameer Parmar el 17 de Jun. de 2016
eye(10);

Jos (10584)
Jos (10584) el 17 de Jun. de 2016
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))

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by