Search code examples
arraysmethodsstructjuliamutable

Using findmin() in data from array composed of mutable struct elements - Julia


Suppose I have the following struct:

mutable struct Car
    load
    locale
    availability
    odometer
end

And I have created an array:

fleet = Vector{Car}(undef, num_cars)

for i in 1:num_cars
   a, b, c, d = rand(4)
   fleet[i] = Car(a, b, c, d)
end

How can I find the smallest (with findmin or similar) or biggest (with?) value from, for example, the odometer of all the cars in my array?

Basically, I want to be able to use conditional statements with struct arrays, e.g.: For every element in my struct array, get the ones that a data satisfy a condition and, from those, get the minimum value of another data.

Thanks!


Solution

  • Finding the minimum value is pretty straightforward, using the minimum function, with a mapping argument:

    julia> minimum(x->x.odometer, fleet)
    0.08468003971220694
    

    If you also want the index of the minimum, you can use the findmin function. Unfortunately, this does not, for some reason, support a function argument, so you have to create a temporary array, and apply findmin to that:

    julia> findmin(getfield.(fleet, :odometer))
    (0.08468003971220694, 1)
    

    You can also use getproperty instead of getfield, they do the same thing for your struct, I'm not certain which is preferable. Probably, the most idiomatic solution would be to define accessor functions instead of using the field values directly. For example:

    odometer(car::Car) = car.odometer
    minimum(odometer, fleet)
    findmin(odometer.(fleet))
    

    For maximum values, use maximum and findmax.