Select a random element of a vector and use randi command

3 views (last 30 days)
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?

Answers (1)

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

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!