programming practices – Selecting nonzero element from numeric array: alternative to For loop?

Basic question to you software developers.

Say I have an array with numeric elements, only one of which is nonzero at any given time.

I need to select just the one nonzero element.

Right now I do this with a For loop that iterates over the entire array, then outputs just the nonzero element.

But is this the best way to do this? And is there an alternative to iterative loops?

One option that comes to mind:

  1. Compare the array elements each to zero. The output would be an array of 1s and 0s, e.g., [1 0 0 0]. This can be done in a single operation without iterative loops in Octave.
  2. Use matrix multiplication to get the product of the original array with the second array. E.g., [2 0 0 0] * [1 0 0 0]’, where ‘ denotes the transpose. The results is 2*1 + 0 + 0 + 0 = 2.
  3. Output the result of the matrix product.

…Would this seem reasonable from a software devel standpoint? It seems more straightforward to implement than a For loop… But I’m not an expert in these things. Thoughts/alternatives?