Storing output in matrix or vector format

I’m new to Julia, coming from Matlab. Consider the following sketched function

function time_stepper(f,u0,nsteps, ...)

# Allocate arrays
t = zeros(nsteps)
p = length(u0)
u = zeros(p,nsteps +1)

# Initialise 
t[1] = 0.0
u[:,1] = u0

# update solution and update u, t

return t, u

While it’s clear that t is a Vector, u may be a vector or a matrix, depending on u0. When p = 1, the code now returns a 1-column matrix, as opposed to a vector. Note I’ve used column-major structure for u, hoping this is good practice in Julia

What should I do to get a more idiomatic Julia code? What’s an appropriate data structure for u here?

Welcome from Matlab!

Your code is type stable regardless of the length of u0, it always returns a Matrix, which is p\times N if u0 is a vector of length p (and if it’s 1\times N that would be similar to a row vector.)

Now, if u0 is a scalar instead of a length-1 vector, your code will fail with an error. In order to work for that situation too, you should add a dot to this expression: u[:, 1] .= u0, then it will work and be type stable in both cases.

If this is not your question, could you elaborate a bit more, for example giving two different example inputs with desired outputs?

(Then a small nitpick: Matlab doesn’t always force you to close a function definition with an end, but it is required in Julia. If you don’t do that, you will get errors or weird results.)

Thanks @DNF, in fact, I threw u[:,1] .= u0 in the full code (and an end, but thanks for pointing this out!).

I’m wondering though if this is good Julia practice? I see that DifferentialEquation.jl, for instance, does not return a matrix for its output in a time stepper, but rather a vector of vectors? I don’t know if this makes sense, and thanks again

Generally speaking, both a vector of vectors and the corresponding matrix can be good practice, depending on how it’s used and the performance characteristics of relevant operations.

Thanks