arraysmatrixjuliadynamic-programmingstochastic-process

Is there a way to implement in Julia an array of matrices with fixed dimension of the array but not of the matrices?


I wanted to create an array of matrices.

I know the size of the array has to be M because I have M matrices; I know those matrices have 2 columns each.

The problem is that I'm trying to start with empty matrices and then add rows to them iteratively, without the constraint of all of the matrices having the same number of rows.

Is there a way to do it?

I already tried constructing a multidimensional array, but this is simply not suitable; I even tried with tuples.

For a better description: I have k reaction and each has a matrix S_k with two columns and undefined number of rows that describes the state if the reaction at each time: so each row is the couple (Time, # of reactions).

Thank you in advance.


Solution

  • Not sure I fully understand the question, but you could create a Vector of Matrices (assuming you know the datatype) via v = Vector{Matrix{Float64}}() and then add Matrices to it by:

    push!(v, [1 2;])
    push!(v, [2 3;])
    push!(v, [4 5;])
    

    Adding rows would require new matrix allocations by concatenation, i.e., v[1] = [v[1]; [6 7;]].

    If you know the number of matrices in advance, you could create them right away, e.g.:

    v2 = [Matrix{Float64}(undef, (0, 2)) for _ = 1:10]
    

    So you wouldn't have to push!, but just add rows via v2[1] = [v2[1]; [1 2;]].

    If performance is important, ElasticArrays.jl may be advantageous. But you may only append along the last dimension:

    v3 = [ElasticArray{Float64}(undef, 2, 0) for _ in 1:10]
    append!(v3[1], [1; 2;;])
    append!(v3[1], [3; 4;;])