What is the best way to flag some elements in MATLAB? using NaN or Inf? or something else?
As you may know, in many occasions, there is a need to flag some elements of a matrix. For example when we have weighted adjacency matrix, and our graph is not fully connec开发者_如何学Goted, we have to flag some elements to show that there is no edge between those nodes. The question is how to do that? Is it better to put NaN or Inf on that elements in the matrix? or something else(such as -1)?
It completely depends on the case. In the example you gave a good solution could be to use zeros, since the edges are weighted, and for many purposes a 0 weight edge is equivalent to no edge. That's true if you're doing stuff like flow/cut algorithms.
Generally when choosing between NaN and Inf, I would go with NaN. Inf has some properties you might not like as an "invalid" marker:
Inf*(-1) = -Inf
Inf+(-Inf) = NaN
Inf > 10 = True
etc...
A clean solution might be to hold another matrix of booleans, that has True where the connection is valid, and False otherwise. It wastes a little memory, but unless your matrix is huge, I think the code readability it will give you is worth it.
精彩评论