每 2 列切片矩阵

发布于 2025-01-19 03:26:37 字数 602 浏览 0 评论 0原文

我试图弄清楚如何每2列切片矩阵。例如,如果有的话

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

,我想返回每2列切片的3个矩阵,即带有3个矩阵的3维数组,

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

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

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

我尝试过的一件事是每个Slice函数,

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]

但是每个列沿每列切片,但是我想切片沿着每两列!

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑咖 2025-01-26 03:26:37

那只是一个重塑。 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索引也是如此:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文