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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With