It is essential to locate the greatest value and its index in a Julia array to spot findmax()
function.
findmax()
functionA useful Julia function for locating the maximum value and its index in an array is findmax()
.
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 .
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")
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