Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array of objects to a function in julia?

Tags:

julia

I want to pass an array of objects to a function and return another array of the same size. How should I do this ? The code should be so fast. For example consider the below code:

struct triangle
    height::Float64
    base::Float64
end

function area(height::Float64, base::Float64)
    return 0.5*base*height
end

I want to define a function which returns the area of an array of triangles. What is the fastest way to do it?

like image 389
bitWise Avatar asked Dec 14 '22 10:12

bitWise


1 Answers

You can leverage Julia's broadcasting syntax for this. Consider:

struct Triangle # Note: Julia convention is to capitalize types
    height::Float64
    base::Float64
end

# Define an area method for the Triangle type
area(t::Triangle) = 0.5 * t.height * t.base

# Create an area of random triangles
triangle_array = [Triangle(rand(), rand()) for _ in 1:10]

# Now we can use dot syntax to broadcast our area function over the array of triangles
area.(triangle_array)

Note that this differs from your code in that it directly uses the Triangle object for dispatch in the call to the area function. The area function then doesn't take height and base arguments but just a single Triangle object and accesses its height and base fields (t.height and t.base).

like image 69
Nils Gudat Avatar answered Jan 05 '23 15:01

Nils Gudat