[英]Randomly select 30% elements in a matrix using MATLAb
I need to do the following for each of elements of a matrix of size mXn: 1. flip a coin with a 0.3 probability of success. 我需要对大小为mXn的矩阵的每个元素执行以下操作:1.翻转成功概率为0.3的硬币。 2. if its a success set the element to zero.
2.如果成功,则将元素设置为零。 3. else move to the next element.
3.否则移到下一个元素。
I used the following code, but it does not give any output and produces NaN, C is the matrix of size mXn: 我使用了以下代码,但没有给出任何输出并产生NaN,C是大小为mXn的矩阵:
index = (rand(size(C)<=0.3));
one_index = find(index ==1);
C(one_index) = 0;
The problem is this statement 问题是这个陈述
index = (rand(size(C)<=0.3));
You've messed up the parentheses so you're trying to compare if size(C) <= 0.3
. 您弄乱了括号,因此您尝试比较
size(C) <= 0.3
。 This returns [0 0]
, causing rand
to create an empty matrix. 这将返回
[0 0]
,导致rand
创建一个空矩阵。
Also, the call to find
is unnecessary. 此外,
find
的电话也是不必要的。
C = magic(4);
index = rand(size(C)) <= 0.3;
C(index) = 0
C =
16 2 3 13
0 11 10 8
9 7 6 0
4 0 15 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.