random matrix with a given number of specified elements
Mostrar comentarios más antiguos
Hello,
How can we generate a matrix n x n Whose elements can be only two values AND where number of one of those two elements is given?
For instance, in the 3 x 3 matrix elements can be only 0 et 1, But I want exactly 4 elements to be zeros (and therefore 5 elements to be ones)
Thank you
2 comentarios
madhan ravi
el 3 de Ag. de 2020
Editada: madhan ravi
el 3 de Ag. de 2020
Did you try something for your homework ?
sko
el 3 de Ag. de 2020
Respuesta aceptada
Más respuestas (1)
Bruno Luong
el 3 de Ag. de 2020
Editada: Bruno Luong
el 3 de Ag. de 2020
User inputs
matsz = [3,3];
n1 = 4; % number of desired 1s, no need to specify for 0s
Generate
B = zeros(matsz); % + 0;
B(randperm(numel(B),n1)) = 1;
Quick check
B
1 comentario
sko
el 3 de Ag. de 2020
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!