Matlab逐元素除以零 [英] Matlab element-wise division by zero
问题描述
我有两个矩阵,比如X = [1 2; 3 4; 5 6],且Y = [0 1; -1 1; 1 1].我想执行按元素除法X./Y,但是我需要一种忽略Y中所有零的方法.
I have two matrices, say X = [1 2; 3 4; 5 6] and Y = [0 1; -1 1; 1 1]. I want to perform element-wise division X./Y, but I need a way to ignore all the zeros in Y.
我尝试使用类似的东西:
I tried using something like:
nonzeros = find(Y〜= 0); X(非零)./Y(非零);
nonzeros = find(Y ~= 0); X(nonzeros) ./ Y(nonzeros);
但是这样做会使结果成为列向量,并且我需要结果矩阵的形状与X(或Y)相同,并且Y为零时为零.因此,在这种情况下,我希望得到的结果是[0 2; -3 4; 5 6].
but doing so caused the result to be a column vector, and I need the shape of the result matrix to be the same as X (or Y) and with zeros where Y was zero. So my desired result for this case is [0 2; -3 4; 5 6].
我还尝试了此处的建议(右数组除法:忽略除法零),但再次执行此操作将强制结果为列向量.
I also tried what was suggested here (Right Array Division : Ignoring division by zeroes), but doing this again forces the result to be a column vector.
谢谢
推荐答案
使用此-
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逐元素除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!