Search code examples
matlabif-statementbsxfun

Write function for bsxfun with if/else


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);

Solution

  • Why not just replace the unwanted values after?

    C=A./B;
    C(A==0 & B==0)=0;
    

    You could do C(isnan(C))=0;, but this will replace all NaN, even the ones not created by 0/0. If zeros always happen together then just C(B==0)=0; will do