Matlab元素划分为零

时间:2014-09-16 20:13:31

标签: matlab

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

我尝试使用类似的东西:

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

但是这样做会导致结果成为列向量,我需要结果矩阵的形状与X(或Y)相同,并且需要零,其中Y为零。所以我对这个案子的期望结果是[0 2; -3 4; 5 6]。

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

由于

1 个答案:

答案 0 :(得分:8)

使用此 -

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
相关问题