Select a random element of a vector and use randi command

조회 수: 5 (최근 30일)
Eric Junaeus
Eric Junaeus 2021년 3월 1일
편집: Eric Junaeus 2021년 3월 2일
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