简体   繁体   English

向矩阵添加随机数MATLAB

[英]Adding a random number to the matrix MATLAB

I want to generate 100x1 matrix with 3 numbers -1,1 and 0. I want to be able to control how much of 1's and -1's are assigned. 我想生成具有3个数字-1,1和0的100x1矩阵。我希望能够控制分配的1和-1中的多少。 I tried using 我尝试使用

 Y = rand(10,1)<0.1 

but this only gives me 0's an 1's. 但这只给我0的1。 But I am able to control the number of 1's in the matrix . 但是我能够控制矩阵中1的数量。 Is there a similar type of function that I can use for adding and controlling the number of -1 and 1's along with the default 0. Sorry I am new matlab env. 有没有可以用于添加和控制-1和1以及默认值0的数量的类似类型的函数。对不起,我是新的matlab env。

Thanks 谢谢

Start by initializing your array: 首先初始化数组:

x = [-1*ones(30,1); zeros(25,1);ones(45,1)];

then use matlab's wonderful indexing with randperm : 然后使用randperm使用matlab的出色索引randperm

y= x(randperm(100));
plot (y, 'o')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM