Julia Function

hi.

kindly help with this. Stuck at it for hours.

How can I implement a Julia function for the product of two matrices AB via dot products, linear combination of columns, linear combination of rows and sum of outer products. A flag should indicate which of the four methods is used.

Can you expand a bit on your use case? It’s bad style to change the output type of a function via an input flag, since it’s a potential source of type instability. It’s more common to use multiple dispatch or write separate methods. If you’re set on using flags, you could write a few methods with a Val flag to dispatch

holaprod(A, B, ::Val{:dotproduct}) = dot(A, B)
holaprod(A, B, ::Val{:columns}) = ...
...

which can then be called with e.g. holaprod(A, B, Val(:dotproduct))

1 Like

I am not facing any issues when writing separate methods.

the challenge comes when I am trying to create one function that allows me to implement all 4 methods within that function.

What I’m saying is that you shouldn’t try to implement all four within one method, since that goes directly against one of the performance tips. Can you write multiple methods with the same name and dispatch using a Val flag as I suggested above? What’s the underlying use case - what are you trying to accomplish by using flags instead of dispatch?

i understand. With flags just wanted to see and understand how the code is affected in terms of performance.

Welcome to the community! If this is a homework question, make sure to indicate that and expect to get only hints on how to solve it yourself, not the solution.

2 Likes

Sure. Thanks for the welcome. understood. Never asked for the solution.

1 Like

I’m not sure I understand the difficulty. If you already know how to do the different implementations, switching between them shouldn’t be more complicated than something like

function my_flexible_matrix_product(A, B, method)
    if method == "method1"
        # code to implement the first method
    elseif method == "method2"
        # code to implement the second method
    else
        error("Unknown method.")
    end
    return result
end
1 Like

Note that the preferred way is to use symbols (:method1) instead of strings ("method1") for such things. I think it’s mostly for performance reasons.

1 Like

Could you please exemplify the use of symbols here?

function my_flexible_matrix_product(A, B, method)
    if method == :method1
        # code to implement the first method
    elseif method == :method2
        # code to implement the second method
    else
        error("Unknown method.")
    end
    return result
end

and then you use it with my_flexible_matrix_product(A, B, :method1).

2 Likes