How to find maxima and it’s indices in Julia array

It is essential to locate the greatest value and its index in a Julia array to spot outliersData outliers are extreme or unusual data points in a dataset that significantly differ from the majority of the data. in data, optimize functionsOptimizing a function involves finding the input values that produce the highest or lowest output, often used in mathematical modeling and machine learning for tasks like parameter tuning or cost minimization., and make choices based on the array's contents. To find the maximum value in an array and its index, we can use the findmax() function.

The findmax() function

A useful Julia function for locating the maximum value and its index in an array is findmax().

Syntax

The syntax for the findmax() function is as follows:

max_value, index = findmax(array)
Syntax of findmax() function

array is the input array in which we want to discover the largest value in it. The maximum value is returned as max_value and its index as index. The first index will be returned if the greatest value occurs more than once in the array.

Note: The indices in Julia starts from index 11 instead of 00.

Code example

Here’s an example demonstrating the usage of findmax() function:

arr = [10, 20, 25, 20, 18, 6, 42]
# Find the maximum value and its index
max_value, index = findmax(arr)
println("Maximum value in an array is: $max_value")
println("Index of maximum value in an array is: $index")

Explanation

Here’s the line-to-line explanation of the above code:

  • Line 1: Initializes the array arr with the given values: [10, 20, 25, 20, 18, 6, 42].

  • Line 4: The findmax() function is applied to the array arr. It returns the maximum value and its index, where the maximum value occurs. Here, max_value stores the maximum value, and index stores the index where the maximum value occurs.

  • Lines 6–7: These two lines print the results. The first line uses string interpolation () to print the maximum value, while the second line prints the index.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved