2
votes

My goal is to use Julia to extract certain columns from a matrix, and then make those columns a new array. For example, in Python, if I define

x=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
y=[1,3]
x[:,y]

This gives me the desired result:

array([[ 2,  4],
       [6,  8],
       [10, 12],
       [14, 16]])

However, in Julia, if I defined

x=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
y=[1 3]
view(x, :, [1 2])

It returns a 4×1×2 array, which is undesirable for what I am doing:

  4×1×2 view(::Array{Int64,2}, :, [1 2]) with eltype Int64:
  [:, :, 1] =
   1
   5
   9
   13

   [:, :, 2] =
   2
   6
   10
   14

How can I write the above code so that my output is 4x2 array; i.e.,

   1   2
   5   6
   9   10
   13  14
1

1 Answers

2
votes

You have written [1 2] which is a 1-row matrix, and should have written [1, 2] which is a vector:

julia> x=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
4×4 Array{Int64,2}:
  1   2   3   4
  5   6   7   8
  9  10  11  12
 13  14  15  16

julia> view(x, :, [1, 2])
4×2 view(::Array{Int64,2}, :, [1, 2]) with eltype Int64:
  1   2
  5   6
  9  10
 13  14