find(A)

find(A)

Return a vector of the linear indexes of the non-zeros in A (determined by A[i]!=0). A common use of this is to convert a boolean array to an array of indexes of the true elements.

Examples

# Find the linear indexes of elements satisfying a condition

# Example 1: Find the indexes of even numbers in an array
julia> arr = [1, 2, 3, 4, 5, 6];
julia> find(iseven, arr)
3-element Array{Int64,1}:
 2
 4
 6

# Example 2: Find the indexes of negative numbers in a matrix
julia> mat = [1 -2 3; -4 5 -6; 7 -8 9];
julia> find(x -> x < 0, mat)
3-element Array{CartesianIndex{2},1}:
 CartesianIndex(2, 1)
 CartesianIndex(3, 2)
 CartesianIndex(2, 3)

# Example 3: Find the indexes of strings containing a specific character in a vector of strings
julia> words = ["apple", "banana", "orange", "grape"];
julia> find(contains("a"), words)
2-element Array{Int64,1}:
 1
 2

# Example 4: Find the indexes of true values in a boolean array
julia> bools = [true, false, true, true, false];
julia> find(identity, bools)
3-element Array{Int64,1}:
 1
 3
 4

The find function returns a vector of linear indexes where the supplied function f returns true for elements in the collection A. The index positions are returned as either Int or CartesianIndex objects, depending on the dimensionality of the collection.

Common mistake example:

julia> arr = [1, 2, 3, 4, 5];
julia> find(x -> x > 5, arr)
Int64[]

In this example, the condition x > 5 does not return true for any element in the array arr, resulting in an empty array as the output. It's important to ensure that the condition provided to find evaluates to true for at least one element in the collection to get non-empty results.

See Also

find, findfirst, findin, findlast, findmin, findn, findnext, findnz, findprev, rsearch, rsearchindex, searchsorted, searchsortedfirst, searchsortedlast, sort, sort!, sortcols, sortperm, sortperm!,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: