Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Array Division : Ignoring division by zeroes

Tags:

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.

like image 539
shujj Avatar asked Jan 28 '26 08:01

shujj


1 Answers

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.

like image 127
Mad Physicist Avatar answered Jan 31 '26 07:01

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!