When there are so many m-files with so many calculations, tracking why this and that went wrong is really a big task.
Often it just turns out that somewhere in the code there was division by 0, or value of Inf saved for some variable.
I want to make this easy to check. One way is to write
if a == Inf
display('a is infinite')
keyboard
end
If I add things like this everytime for every variable, it will work but it will be messy.
Can I make MatLab stop or pause or pop up a warning message if some variable is Inf in the process of running?
解决方案
Matlab has a nice debugging suite for a number of on-the-fly conditions.
In particular, the command1
dbstop if naninf
which will pause execution a line after a NaN or Inf condition is found. An example is given on the documentation. The only potential downside of using this feature is that the pause occurs if any variables are initialized as NaN or Inf, which some codes do (to my confusion).
dbstop does have a more pinpoint and potentially robust system of pausing execution, but I think the naninf option combined with good tests is an excellent place to start for general development.
1 The same behavior can be invoked from the GUI by going to Breakpoints > More Error and Warning Handling Options > NaN or Inf and selecting the correct radio button.