Select a random element of a vector and use randi command

5 visualizaciones (últimos 30 días)
Eric Junaeus
Eric Junaeus el 1 de Mzo. de 2021
Editada: Eric Junaeus el 2 de Mzo. de 2021
What command should I use to randomly select an element from a vector and give it a random number by using the randi command while also displaying the other elements in the workspace?

Respuestas (1)

KSSV
KSSV el 1 de Mzo. de 2021
A = magic(5) ;
A = A(:) ;
N = numel(A) ;
idx = randi(N,1) ;
A(idx) = rand
  1 comentario
Eric Junaeus
Eric Junaeus el 2 de Mzo. de 2021
Editada: Eric Junaeus el 2 de Mzo. de 2021
Thanks for the reply!
I have made my own code based on yours:
A = zeros(1,10);
N = numel(A);
idx = randi(N);
A(idx) = randi(10);
I would like to create a while loop that makes sure that as long there are any zeros in my vector, any of the elements will get a random number. I tried using any(A == 0) but it seems to give all elements at once a random number. Is it possible to add a random number to just one element at a time, save the value for that particular element, add another random number to any element, either to a different element or the same element that already has a random number (thus incrementing the random number to the already existing number) until all elements have a value of at least 1, necessitating the use of the all(A) command? Could if so could you also add comments to your code?

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices 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