Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marginalise over n dimensional array

I am trying to figure out how to handle multidimensional arrays in julia. I have a multidimensional array A = rand(5,5,5).

I am trying to figure out how to get A[1,1,:] or A[1,:,1] or A[:,1,1] with the position of the : given by an input m.

I have come up with

indexData = [:,1,2]
indexData[1],indexData[m] = indexData[m],indexData[1]
data = A[indexData[1],indexData[2],indexData[3]]

but this seems overly complicated and would not scale if the dimension of A was unknown. Is there some better ways of solving this?

like image 593
drd13 Avatar asked Oct 30 '16 14:10

drd13


1 Answers

The following might fit the bill:

getshaft(A,ii,m) = [A[(i==m?j:ii[i] for i=1:length(ii))...] for j=1:size(A,m)]

Consider the following example:

julia> A = reshape(collect(1:27),3,3,3)
3×3×3 Array{Int64,3}:
[:, :, 1] =
 1  4  7
 2  5  8
 3  6  9

[:, :, 2] =
 10  13  16
 11  14  17
 12  15  18

[:, :, 3] =
 19  22  25
 20  23  26
 21  24  27

julia> getshaft(A,(1,2,3),1)
3-element Array{Int64,1}:
 22
 23
 24

The second parameter is an element index, and the third chooses a dimension. getshaft will return the vector of values including the element selected by the second parameter along the dimension specified by the third parameter. The first parameter is, of course, the array.

--- Update ---

A quick review, suggested an even faster and cleaner implementation of the same function:

getshaft(A,ii,m) = A[(i==m?Colon():ii[i] for i=1:length(ii))...]

Using slice indexing might benefit from faster index calculations or other AbstractArray sorcery in the background.

like image 199
Dan Getz Avatar answered Oct 20 '22 09:10

Dan Getz