How to compute the correlation between elements in an array of arrays?

Suppose that I have the following array of vectors.

temp = Matrix{Vector{Float64}}(undef, 3, 1000)
for i = 1:3
    for j = 1:1000
        temp[i,j] = rand(10)
    end
end

Now I want to compute the correlation between the first element in the inner-vector and the second element in the inner-vector, separately for each row dimension of the outer-matrix. I was trying to do something like this:

cor(temp[1,:][1,:], temp[1,:][2,:])

But temp[1,:][1,:] only gives me the first vector , rather then collecting horizontally the first elements in all vectors in the first row of the outer-matrix.

You can define your own slicing function

julia> AoV_row(arr, row, idx) = getindex.(arr[row, :], idx)
AoV_row (generic function with 1 method)

julia> cor(AoV_row(temp,1,1), AoV_row(temp,1,2))
0.0036541528935823526
1 Like

Wow, this is much better than my for loop code. So, there is no direct way say temp[i,j] to do it. Thank you.

1 Like

If you want slicing to be more convenient you would be better off with a 3-dimensional array than a matrix of vectors.

2 Likes

Thanks, I will also think about it.