根据另一个矩阵中相应元素的值更改矩阵中的元素

时间:2016-10-07 01:14:15

标签: matlab matrix random

首先,我想生成一个随机矩阵,其大小与输入矩阵相同。如果随机矩阵中的元素值大于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] 

1 个答案:

答案 0 :(得分:0)

您可以使用逻辑索引创建true值的矩阵,其中Random大于0.5,而false则为Random = rand(size(X)); greater_than_one_half = Random > 0.5;

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; 的某些元素。

~

或者你可以做一些聪明的事情并使用逻辑数组的否定(-1)作为false的指数,这样当它-1(0)时,它是-1^(~0)true),当它是1(1)时,它是-1^(~1)X) 。然后将其添加到X = X + (-1).^(~greater_than_one_half);

X = X + (-1).^(Random <= 0.5);

或者简单地说:

{{1}}