Create random values in vector Matlab

2019-09-14 23:39发布

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?

2条回答
神经病院院长
2楼-- · 2019-09-15 00:06

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
查看更多
Ridiculous、
3楼-- · 2019-09-15 00:12

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)).

查看更多
登录 后发表回答