Avoid division by zero between matrices in MATLAB [duplicate]

橙三吉。 提交于 2020-01-24 08:41:16

问题


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 ?


回答1:


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;



回答2:


One option would be to preallocate x and then only use division on the parts where m is not zero.

x = zeros(size(m)); % output is same size as m
n = m~=0;  % find indexes
x(n)=G(n)./m(n); 


来源:https://stackoverflow.com/questions/27122456/avoid-division-by-zero-between-matrices-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!