# find

find partially overloads the find operator on a vector. The find operator returns the index to the **first** non-zero value of a vector. If there is no non-zero value, the index is defined as **length(x)+1** (as a decision variable cannot be empty, which would be MATLAB standard for the find operator).

### Syntax

```
[index,value] = find(x)
```

### Examples

The following problem should lead to the last element of **x** set to 1 and all other elements zero.

```
x = sdpvar(1,5);
y = binvar(1,5);
[index,nonzerovalue] = find(x);
optimize([x == y, sum(y)==1, -10 <= x <= 10],-index);
```

Since the index can be larger than the length of the vector to handle the case with no non-zeroes, one should not use the found index for indexing as in ‘‘x(index)’’ (unless we know there will be a non-zero) but instead use the second output (which will be 0 if there are nonzeros). The following model should lead to **x=0** with **nonzerovalue=0**.

```
x = sdpvar(1,5);
y = binvar(1,5);
[index,nonzerovalue] = find(x);
optimize([x == y, -10 <= x <= 10],nonzerovalue);
```

### Comments

The operator is implemented using a mixed-integer model based on big-M approach, hence it is crucial that all involved variables have explicit bound constraints.

Most often, you can create a model without using the find operator, and resorting to this this operator is typically a sign of a model which you can describe in a better form.

## Leave a Comment