Creating random values ​​in a Matlab vector

I have this vector:

Population = [3, 5, 0, 2, 0, 5, 10, 50, 0, 1];

And I need to fill this vector with a random value between 1 and 4, only if the vector has a value of 0.

How can i do this?

Edit: is there a way to do this using the randperm function?

0
source share
2 answers

First find the null elements, then generate random values, then replace these elements:

Population = [3, 5, 0, 2, 0, 5, 10, 50, 0, 1]; idx = find(Population==0); Population(idx) = 3 * rand(size(idx)) + 1; 

If you need integers (do not specify), simply round the generated random numbers in the last statement, for example, this is round(3*rand(size(idx))+1) ; or use randi (as pointed out by @OmG's answer): randi([1,4], size(idx)) .

0
source

You can use the following code:

 ind = find(~Population); % find zero places Population(ind) = randi(4,1,length(ind)); % replace them with a random integer 
0
source

Source: https://habr.com/ru/post/1274486/


All Articles