Home > Net >  Slice matrix every 2 columns
Slice matrix every 2 columns

Time:04-06

I am trying to figure out how to slice a matrix every 2 columns. For example, if we have

A=[[1 2 3 4 5 6];[7 8 9 10 11 12]]

2×6 Matrix{Int64}:
 1  2  3   4   5   6
 7  8  9  10  11  12

then I would like to return 3 matrices sliced every 2 columns, i.e. a 3 dimensional array with 3 matrices,

2×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  2
 7  8

[:, :, 2] =
 3   4
 9  10

[:, :, 3] =
  5   6
 11  12

One thing I have tried is the eachslice function,

collect(eachslice(A,dims=2))

6-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
 [1, 7]
 [2, 8]
 [3, 9]
 [4, 10]
 [5, 11]
 [6, 12]

but this slices along every column, but I want to slice along every two columns!

Thanks in advance.

CodePudding user response:

That's just a reshape. Reshapes share memory (like views), so you should copy it if you want it to be independent of the original A:

julia> reshape(A, 2, 2, 3)
2×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  2
 7  8

[:, :, 2] =
 3   4
 9  10

[:, :, 3] =
  5   6
 11  12

But if you really want, you can express it as indexing, too:

julia> A[:, [1:2 3:4 5:6]]
2×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  2
 7  8

[:, :, 2] =
 3   4
 9  10

[:, :, 3] =
  5   6
 11  12
  • Related