Select a random element of a vector and use randi command

4 visualizzazioni (ultimi 30 giorni)
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?

Risposte (1)

KSSV
KSSV il 1 Mar 2021
A = magic(5) ;
A = A(:) ;
N = numel(A) ;
idx = randi(N,1) ;
A(idx) = rand
  1 Commento
Eric Junaeus
Eric Junaeus il 2 Mar 2021
Modificato: Eric Junaeus il 2 Mar 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?

Accedi per commentare.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by