How to build a matrix where each element is a vector

Hi all,
Iโ€™m looking for the best way to construct a matrix where each element is an actual vector.
More specifically, if I have:

fs = 10 # Sampling Frequnecy [Hz]
๐‘“ = 1e-3 # Forcing frequency [Hz]
t_end = 10^4
t = collect(0.0:1/fs:t_end)
ฯ• = [ฯ€/6, ฯ€/9, ฯ€/7.5, ฯ€/3]
a = [0.001, 0.003, 0.004]

I want to create a matrix where each element is a time-series:

Matrix[i,j] = @. sin(2*ฯ€*๐‘“*t - ฯ•[i]) + a[j]*t

I know this should be simple, but I canโ€™t find the best way to do it for some reason.
In addition, is there a way to build this matrix dynamically with push! too?

Thank you!

[@. sin(2*ฯ€*๐‘“*t - ฯ•[i]) + a[j]*t for i in 1:4, j in 1:3]

would be one possibility (using comprehension, see Single- and multi-dimensional Arrays ยท The Julia Language )

4 Likes

One other way is:

julia> m = Matrix{Vector{Float64}}(undef, length(ฯ•), length(a));

julia> for i in 1:4, j in 1:3
           m[i,j] = @. sin(2*ฯ€*๐‘“*t - ฯ•[i]) + a[j]*t
       end
3 Likes

BTW, donโ€™t use collect here, thereโ€™s no point.

3 Likes

Also, a minor point, but consider using sinpi for stuff like this. It will be a bit more accurate and imo, cleaner.

2 Likes