findprev(A,i)

findprev(A, i)

Find the previous index <= i of a non-zero element of A, or 0 if not found.

Examples

  1. Find the previous index of a matching element in an array:

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

    In this example, the findprev function is used to find the index of the previous element in arr that is greater than 3.

  2. Find the previous index of a matching element in a vector of strings:

    julia> words = ["apple", "banana", "orange", "grape"];
    julia> findprev(x -> length(x) > 5, words, 4)
    2

    This example demonstrates finding the index of the previous string in words that has a length greater than 5.

  3. Handle cases where no matching element is found:
    julia> numbers = [1, 2, 3, 4];
    julia> findprev(x -> x == 5, numbers, 3)
    0

    In this case, the findprev function returns 0 since there is no element in numbers that satisfies the predicate.

Common mistake example:

julia> arr = [10, 20, 30, 40];
julia> findprev(x -> x > 50, arr, 4)
ERROR: BoundsError: attempt to access 4-element Array{Int64,1} at index [5]

In this example, an IndexError occurs because the predicate never returns true, causing the function to search beyond the bounds of the array. It is essential to ensure that the predicate has a matching condition to avoid such errors.

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: