Result of a function is a 3x6 matrix

Dear all,

I started to use Julia a week ago, by porting one of my existing computational fluid dynamics solvers to Julia. A subroutine I am currently working on is creating a 3x6 matrix of Float64s. In Fortran or C++ I would send a reference to the matrix to a subroutine or function, it would work on its contents and results would be available in the body of the code which called it.

I am not quite sure how to approach it in Julia. I understand that Julia is all about returning values from function calls, but I somehow feel that forming a 3x6 matrix inside a function and returning it as a result would create an overhead in terms of memory allocation/deallocation and copying. Shall I put it inside a container (struct) and send that to the function instead? Would that be in line with Julia’s best practices? I don’t know.

I would appreciate any hint.

Cheers

GitHub - JuliaArrays/StaticArrays.jl: Statically sized arrays for Julia may help here rather than using standard Arrays. You could also just pass it to your function and mutate it like you would in Fortran or C++, there’s nothing particularly wrong with doing that.

2 Likes

A regular array is already a mutable container - no need for just wrapping in an additional struct (though using the struct to bundle multiple arrays into one is good).

You can just assign to the indices of a passed array and the values will be visible outside:

julia> a = zeros(3,6)
3×6 Matrix{Float64}:
 0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0

julia> function myFunc!(arr)
         arr[1,2] = 5.0
       end
myFunc! (generic function with 1 method)

julia> myFunc!(a)
5.0

julia> a
3×6 Matrix{Float64}:
 0.0  5.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0

Note that 5.0 in the last display.

The exclamation mark is just a notational convention, to signal to users that the function is modifying one or more of its arguments. This behavior works for any mutable struct/container.

5 Likes

inbuilt functions in general are fine. But cell is a much more versatile datatype than matrix. As such it should not be a surprise that usually it is more efficient to operate on the matrix, rather than converting it to a cell, operating on the cell, and converting it to a matrix. – For small problems efficiency may not be a concern, but in that case I would still argue that it is best practice for code clarity, to stick to matrices unless there is a compelling reason not to.