Is there any way to use max() and min() based on a function?

This is easily done in, for example, Python, and can be very useful. I have spent quite a bit of time searching documentation and reading forum questions, without finding anything.

Here’s a small example of what I would like to do:

arr = [1,2,3,4,-5]
sqmax = max(arr, by = x -> x^2)

I know this can be done as follows, but it seems like it would make sense for max() to have a by option.

sqmax = sort(arr, by = x -> x^2)[end]

You are looking for what is called maximum in Julia. Take a look at the documentation on max and maximum for more examples.

Welcome to the forum. A question like this is better suited for the “Usage” category.

2 Likes

But still there is no built in maxiumum function offering whats requested.

I’d go with:
findmax(map(x->x^2,arr))

Update: this is only needed if you want the index, which I initially thought was asked.

maximum does take an optional function as its first argument. Try maximum(x -> x^2, arr).

2 Likes

why not:

maximum(arr.^2)

The problem with that is that it creates a temporary array, which can be avoided by passing the function as an argument.

That allocates an intermediate array for the squared array whereas the version from simon does not. It would be nice if we could reduce over a broadcasted array without allocs one day but we’re not there yet.