[英]Change the element in a matrix based on the value of the corresponding element in another matrix
First of all I want to generate a random matrix which size is the same as the input matrix. 首先,我想生成一个随机矩阵,其大小与输入矩阵相同。 If an element value in random matrix is greater than 0.5 , then l have to increment the value of corresponding element in the input matrix by one, else decrement by 1.
如果随机矩阵中的元素值大于0.5,则l必须将输入矩阵中相应元素的值加1,否则减1。
X=[4 5 6 ; 7 8 9 ; 3 2 1]
Random=[ 0.65 0.43 0.23 ; 0.75 0.12 0.78 ; 0.31 0.96 0.58]
You can use logical indexing to create a matrix of true
values where Random
is greater than 0.5
and false
otherwise. 您可以使用逻辑索引创建一个
true
值矩阵,其中Random
大于0.5
,否则0.5
false
。
Random = rand(size(X));
greater_than_one_half = Random > 0.5;
You can then use this logical matrix to select and manipulate certain elements of X
or Y
. 然后,您可以使用此逻辑矩阵来选择和操纵
X
或Y
某些元素。
% Add one to all values in X where Random > 0.5
X(greater_than_one_half) = X(greater_than_one_half) + 1;
% Subtract one from all values in X where Random <= 0.5
X(~greater_than_one_half) = X(~greater_than_one_half) - 1;
Or you could do something clever and use the negation ( ~
) of the logical array as an exponent for -1
such that when it's false
(0), it's -1
( -1^(~0)
) and when it's true
(1), it's 1
( -1^(~1)
). 或者,您可以做一些聪明的事,并将逻辑数组的负数(
~
)用作-1
的指数,这样当它为false
(0)时为-1
( -1^(~0)
)而当它为true
(1 ),它是1
( -1^(~1)
)。 Then add this to X
. 然后将此添加到
X
X = X + (-1).^(~greater_than_one_half);
Or simply: 或者简单地:
X = X + (-1).^(Random <= 0.5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.