In my code, I need to divide each values of a matrix by the values of another. I could use A./B
but some elements in B are 0. I know that if B(i,j) = 0 so A(i,j) = 0 too and I want to have 0/0 = 0. So I wrote a function div and I use bsxfun but I don't have 0, I have NaN :
A = [1,0;1,1];
B = [1,0;1,2];
function n = div(a,b)
if(b==0)
n = 0;
else
n = a./b;
end
end
C = bsxfun(@div,A,B);
Why not just replace the unwanted values after?
You could do
C(isnan(C))=0;
, but this will replace allNaN
, even the ones not created by0/0
. If zeros always happen together then justC(B==0)=0;
will do