本文介绍了右数组除法:忽略被零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个尺寸相似的数据矩阵AB.我打算将的每个元素除以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);

使用逻辑索引时,将仅评估与ttrue元素相对应的ABC元素. ttrue,仅当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.

这篇关于右数组除法:忽略被零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:31