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?
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With