在向量Matlab中创建随机值 [英] Create random values in vector Matlab

查看:197
本文介绍了在向量Matlab中创建随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个向量:

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

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

我只需要在向量中具有0值的地方用1到4之间的随机值来填充此向量.

And i need to fill this vector with a random value between 1 and 4 only where have 0 value in vector.

我该怎么做?

有一种方法可以使用randperm函数吗?

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

推荐答案

首先,找到零个元素,然后生成随机值,然后替换这些元素:

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;

如果需要整数(未指定),只需在最后一条语句中四舍五入生成的随机数,例如round(3*rand(size(idx))+1);或使用randi(如@OmG的回答所建议):randi([1,4], size(idx)).

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

这篇关于在向量Matlab中创建随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆