user12345
user12345

Reputation: 127

How to find one zero element in a vector

How can I find one 0 in a vector efficiently, supposing there is at least one zero in that vector?

Suppose that there is a vector v = [1; 0; 1; 3; 4; 0; 0]. I know that find(v==0) will return all the indices of the zero elements of v, but since I only want one of these zeros, any which one is ok, this seems not very efficient. Is there a better way, or should I use for of while loops?

Upvotes: 0

Views: 470

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

In practice

In a normal situation, I would consider it best practice to use the most simple solution, that is already mentioned in the comments:

find(~v,1)

Theoretical improvement

Note that it does perform an operation on the complete vector, as it first evaluates it completely to determine whether it is nonzero.

If you were to have a very long vector, and would expect to find a zero very fast (e.g. in the first log(n) entries) , it would in give you a better complexity to use a while loop, that stops upon finding the zero.

That being said, vector operations are very efficient, and loops have some overhead. Therefore I would be suprised if a loop turned out to be faster than a find.


Going for the optimum

Of course all of this is how it should work, if you really want to get the best performance, it all reduces to the basic rule of finding what works fastest:

Try all alternatives and see what actually works fastest for your solution

Upvotes: 1

Adriaan
Adriaan

Reputation: 18177

find(v==0,1,'first') will give you only a single zero instance, namely the first. Same goes for find(v==0,1,'last'), which will give you the last. Since find then terminates after the first encounter with a zero (either from top or bottom) it will be faster.

You mention any one is OK, thus this will work. For a random 0 it'd be more involved.

Upvotes: 3

Related Questions