【问题标题】:Matlab element-wise division by zeroMatlab逐元素除以零
【发布时间】:2014-09-17 04:41:41
【问题描述】:

我有两个矩阵,比如 X = [1 2; 3 4; 5 6] 和 Y = [0 1; -1 1; 1 1]。我想执行逐元素除法 X./Y,但我需要一种方法来忽略 Y 中的所有零。

我尝试使用类似的东西:

非零 = find(Y ~= 0); X(非零) ./ Y(非零);

但是这样做会导致结果是一个列向量,我需要结果矩阵的形状与 X(或 Y)相同,并且在 Y 为零时使用零。所以我对这种情况的期望结果是 [0 2; -3 4; 5 6]。

我也尝试了这里的建议 (Right Array Division : Ignoring division by zeroes),但再次这样做会强制结果为列向量。

谢谢

【问题讨论】:

    标签: matlab


    【解决方案1】:

    使用这个 -

    out = X./Y      %// Perform the elementwise division
    out(Y==0)=0     %// Select the positions where Y is zero and 
                    %// set those positions in the output to zero
    

    输出 -

    X =
         1     2
         3     4
         5     6
    Y =
         0     1
        -1     1
         1     1
    out =
         0     2
        -3     4
         5     6
    

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2016-08-13
      • 2015-01-08
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多