【问题标题】:Change the element in a matrix based on the value of the corresponding element in another matrix根据另一个矩阵中对应元素的值改变一个矩阵中的元素
【发布时间】:2016-10-07 01:14:15
【问题描述】:

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

【问题讨论】:

  • XY 是什么?你要修改哪一个?
  • 我要修改X,Y是输出。

标签: matlab matrix random


【解决方案1】:

您可以使用逻辑索引创建true 值的矩阵,其中Random 大于0.5,否则false

Random = rand(size(X));
greater_than_one_half = Random > 0.5;

然后您可以使用此逻辑矩阵来选择和操作XY 的某些元素。

% 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 (0) 时,它是 -1 (-1^(~0)) 和当它是true (1) 时,它是1 (-1^(~1))。然后将此添加到X

X = X + (-1).^(~greater_than_one_half);

或者简单地说:

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

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多