gpt4 book ai didi

python-3.x - Julia 的 reshape

转载 作者:行者123 更新时间:2023-12-02 07:27:16 27 4
gpt4 key购买 nike

如果我在 python 中 reshape 我使用这个:

import numpy as np

y= np.asarray([1,2,3,4,5,6,7,8])
x=2
z=y.reshape(-1, x)


print(z)

得到这个
>>> 
[[1 2]
[3 4]
[5 6]
[7 8]]

我怎么能在 Julia 得到同样的东西?我试过:
z = [1,2,3,4,5,6,7,8]
x= 2
a=reshape(z,x,4)

println(a)

它给了我:
[1 3 5 7
2 4 6 8]

如果我使用 reshape(z,4,x)它会给
[1 5
2 6
3 7
4 8]

还有一种方法可以在不指定第二维的情况下进行整形,如 reshape(z,x)或者如果二级维度更模糊?

最佳答案

我想你遇到的是NumPy stores in row-major orderJulia stores arrays in column major order如上所述here .

所以 Julia 正在做如果你使用 numpy 会做的事情

z=y.reshape(-1,x,order='F')

您想要的是第一次尝试的转置,即
z = [1,2,3,4,5,6,7,8]
x= 2
a=reshape(z,x,4)'

println(a)

你想知道假设数组是二维的,是否有东西可以计算二维?从来没听说过。可能 ArrayViews ?这是一个简单的函数开始
julia> shape2d(x,shape...)=length(shape)!=1?reshape(x,shape...):reshape(x,shape[1],Int64(length(x)/shape[1]))
shape2d (generic function with 1 method)

julia> shape2d(z,x)'
4x2 Array{Int64,2}:
1 2
3 4
5 6
7 8

关于python-3.x - Julia 的 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com