Create random values in vector Matlab

2019-09-14 23:36发布

问题:

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 where have 0 value in vector.

How i can do it ?

Edit: there's a way to do it using randperm function?

回答1:

First, find zero elements, then generate random values, then replace those 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 (didn't specify), just round the generated random numbers in the last statement, like this round(3*rand(size(idx))+1); or use randi (as suggested in answer by @OmG): randi([1,4], size(idx)).



回答2:

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