Select a random element of a vector and use randi command

5 次查看(过去 30 天)
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?

回答(1 个)

KSSV
KSSV 2021-3-1
A = magic(5) ;
A = A(:) ;
N = numel(A) ;
idx = randi(N,1) ;
A(idx) = rand
  1 个评论
Eric Junaeus
Eric Junaeus 2021-3-2
编辑:Eric Junaeus 2021-3-2
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?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by