randomizing location of N zeros in matrix of ones

I need to make a matrix of ones (say 20X20).
Inside that matrix I need zero to appear randomly (in random locations) N times.

 Respuesta aceptada

Matt Fig
Matt Fig el 6 de Feb. de 2011
EDIT: Thanks to Jan Simon for nitpicking ;-).
Say you want a 20-by-20 matrix of zeros with 7 ones put in:
N = 7;
A = ones(20);
B = randperm(numel(A));
A(B(1:N)) = 0

2 comentarios

Tali
Tali el 7 de Feb. de 2011
thank you so much! (made my day!)
Jos (10584)
Jos (10584) el 7 de Feb. de 2011
See http://www.mathworks.com/matlabcentral/fileexchange/10924-ntrue

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 7 de Feb. de 2011
EDITED: First version completely deleted after Walter found out, that Matt's algorithm works ~30% faster.
For larger matrices RANDPERM is slow. You can use the C-mex Shuffle from the FEX instead: http://www.mathworks.com/matlabcentral/fileexchange/27076
N = 7;
M = 20;
A = ones(M);
A(Shuffle(numel(A), 'index', N)) = 0;
For M=20, N=7 this is 4 times faster, for M=200, N=70 this is even 30 times faster than the method using RANDPERM.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 6 de Feb. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by