我有两个矩阵,比如 X = [1 2; 3 4; 5 6] 和 Y = [0 1; -1 1; 1 1]。我想执行逐元素除法 X./Y,但我需要一种方法来忽略 Y 中的所有零。
我尝试使用类似的东西:
非零 = 查找(Y ~= 0); X(非零) ./Y(非零);
但这样做会导致结果成为列向量,我需要结果矩阵的形状与 X(或 Y)相同,并且在 Y 为零的地方使用零。所以我对这种情况的期望结果是 [0 2; -3 4; 5 6].
我也尝试了这里建议的方法 ( Right Array Division : Ignoring division by zeroes ),但再次这样做会强制结果成为列向量。
谢谢
最佳答案
使用这个-
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
关于Matlab逐元素除以零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877625/