问题描述
我有两个尺寸相似的数据矩阵A
和B
.我打算将的每个元素除以B
的相应元素.为此,matlab提供了一个快捷方式,如C = A./B
.但是,B
有许多零元素,对于这些元素,我希望C
的元素为零而不是NAN
. MATLAB是否提供有效的方式来做到这一点?我可以循环执行此操作,但这将非常昂贵.谢谢.
I have two data matrices A
and B
of similar dimensions. I intend to divide each element of A
by its corresponding elements of B
. For this matlab provides a shortcut as C = A./B
. However, B
has many zero elements , for such elements I want elements of C
to be zero rather than NAN
. Does MATLAB provide a way to do this in an efficent manner? I could do this in a loop but that would be very expensive.Thanks.
推荐答案
是.您可以使用逻辑索引:
Yes. You can use logical indexing:
C = zeros(size(A));
t = logical(B);
C(t) = A(t)./B(t);
使用逻辑索引时,将仅评估与t
的true
元素相对应的A
,B
和C
元素. t
是true
,仅当B
不为零时.请注意,C
被预先初始化为零,以自动处理由于B
为零而未被评估的情况.
With logical indexing, only the elements of A
, B
and C
corresponding to true
elements of t
will be evaluated. t
is true
only where B
is non-zero. Note that C
is pre-initialized to zeros to automatically take care of the cases that are not evaluated because B
is zero.
这篇关于右数组除法:忽略被零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!