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 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)
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
instead of .
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 indexmax_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
arrwith the given values:[10, 20, 25, 20, 18, 6, 42]. -
Line 4: The
findmax()function is applied to the arrayarr. It returns the maximum value and its index, where the maximum value occurs. Here,max_valuestores the maximum value, andindexstores 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