问题
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