Randomly change the location of 1s on a matrix of 0s (randperm on a matrix}
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Doobie
el 29 de Abr. de 2017
Respondida: Image Analyst
el 29 de Abr. de 2017
How does one generate a random matrix that satisfies certain properties? Specifically, I'm looking for a code that does this:
Given the matrix below, I want to randomly change the locations of 1s.
1 0 0
1 0 0
0 0 0
0 0 0
So examples would be
1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0
0 0 0 0 1 0 1 0 0
0 0 0 1 0 0 0 0 0
Well the initial matrix is easy enough.
A = zeros(4,3);
A(1:2,1) = ones(2,1);
But I don't know how to proceed from here. randperm() only generates a vector so doesn't work here. Is there a matlab function that does what randperm does on a matrix?
0 comentarios
Respuesta aceptada
Image Analyst
el 29 de Abr. de 2017
Here's one way:
m=[...
1 0 0
1 0 0
0 0 0
0 0 0]
[rows, columns] = size(m);
ne = numel(m)
numOnes = sum(m(:))
% Generate 10 new versions with 1's in different locations each time.
for k = 1 : 10
m2 = zeros(size(m)); % Initialize
m2(randperm(ne, numOnes)) = 1;
% Turn from vector into 2-D matrix
m2 = reshape(m2, rows, columns)
end
0 comentarios
Más respuestas (1)
Star Strider
el 29 de Abr. de 2017
See How to place a number in a random position in a matrix of zeros? (link) for one approach. You can create more random 1 values by having the randi function return a vector rather than a single value. See the documentation for the randi function for details.
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!