Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid division by zero between matrices in MATLAB [duplicate]

I'm using matlab and I have two matrices :

G =

 1     1     1     1
 1     1     1     1

and the scond:

m =

 4     4     4     4
 0     0     0     0

I want this result :

x =

 1/4     1/4     1/4     1/4
  0       0       0       0

What I did so far is this :

x = G ./ m

But it returns :

x =

 1/4     1/4     1/4     1/4
 NaN     NaN     NaN     NaN

How can I avoid the divison by zero by placing a default value "0" if there is a division by zero ?

like image 256
deltascience Avatar asked Feb 11 '23 12:02

deltascience


1 Answers

You can convert the NaNs back to zero:

x = G ./ m;
x(isnan(x))=0;      % thanks to comment by @nkjt

Or, if you have also NaNs in matrix m that you want to save, you can do:

x(m==0)=0;
like image 184
Adiel Avatar answered Feb 15 '23 09:02

Adiel