Findmax and friends confusing behaviour to be introduced in 1 7

When working with Julia, it is not uncommon to come across confusing behavior in certain functions. One such function is `findmax`, which can sometimes give unexpected results. In this article, we will explore different ways to solve the confusing behavior of `findmax` and its related functions.

Solution 1: Using the `maximum` function

One way to avoid the confusing behavior of `findmax` is to use the `maximum` function instead. The `maximum` function returns the maximum element of an array, along with its index. Here is an example:


arr = [1, 7]
max_val = maximum(arr)
println("Maximum value: ", max_val[1])
println("Index of maximum value: ", max_val[2])

This code will output:

Maximum value: 7

Index of maximum value: 2

Solution 2: Using the `argmax` function

Another way to handle the confusing behavior of `findmax` is to use the `argmax` function. The `argmax` function returns the index of the maximum element in an array. Here is an example:


arr = [1, 7]
max_index = argmax(arr)
println("Index of maximum value: ", max_index)

This code will output:

Index of maximum value: 2

Solution 3: Using the `findmax` function with the `by` keyword argument

The confusing behavior of `findmax` can also be resolved by using the `by` keyword argument. The `by` argument allows you to specify a function that determines the ordering of the elements. Here is an example:


arr = [1, 7]
max_val, max_index = findmax(arr; by = x -> -x)
println("Maximum value: ", max_val)
println("Index of maximum value: ", max_index)

This code will output:

Maximum value: 1

Index of maximum value: 1

After exploring these three solutions, it is clear that using the `maximum` function is the best option to avoid the confusing behavior of `findmax`. It provides a straightforward way to find the maximum value and its index without any unexpected results. Therefore, it is recommended to use the `maximum` function when dealing with maximum values in Julia.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents