can anybody give me a example showing how to avoid division by 0 by using try-catch?

9 次查看(过去 30 天)
can anybody give me a example showing how to avoid division by 0 by using try-catch? thank you very much!
  2 个评论
Jan
Jan 2011-10-7
TRY-CATCH does not *avoid* the division by zero. In opposite: The term "try" means, that MATLAB tries to calculate the division and calls the CATCH block, if an error occurs.
Lin LI
Lin LI 2011-10-7
thank you , Jan, I am trying to do some integration , what i mean is that when the denominator is 0 ,I want to replace the denominator with a another nonzero number, so that i can continue to do integration. can I use the try to detect division by 0 warning, then use the catch to replace the denominator. can you show me the code?

请先登录,再进行评论。

采纳的回答

Grzegorz Knor
Grzegorz Knor 2011-10-7
Dividing by zero does not return an error in Matlab. So I suggest you to use if - else instead try - catch:
for k = -5:5
if k~=0
x = 1./k;
disp(x)
else
disp('you try divide by zero!')
end
end
  3 个评论
Lin LI
Lin LI 2011-10-7
thank you , Grzegorz and andrei, I am trying to do some integration , what i mean is that when the denominator is 0 ,I want to replace the denominator with a another nonzero number, so that i can continue to do integration. can I use the try to detect division by 0 warning, then use the catch to replace the denominator. can you show me the code?
Walter Roberson
Walter Roberson 2011-10-7
I do not remember the details at the moment, but I seem to recall that division by zero is noticed and reported via a warning or error (I do not remember which), except that that warning or error is turned off by default.

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2011-10-7
Don't do that. Do like I recommended earlier: calculate the denominator and assign the result to a variable, and test the range of the variable, and take appropriate corrective action if it is smaller than you want.

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by