在 Julia 中添加 3-D 数组的 2-D 数组和 2-D 子数组时出错
Error when adding 2-D array and 2-D subarray of 3-D array in Julia
为什么当我 运行 以下代码时 Julia 会抛出错误?
毕竟,A[1,:,:]
在逻辑上是一个二维数组。
如果我没记错的话,类似的代码可以在 MATLAB 中运行。
julia> A = reshape(1:8, 2, 2, 2)
2x2x2 Array{Int64,3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
5 7
6 8
julia> B = reshape(1:4, 2, 2)
2x2 Array{Int64,2}:
1 3
2 4
julia> B + A[1,:,:]
ERROR: dimensions must match
in promote_shape at operators.jl:211
in promote_shape at operators.jl:207
in + at array.jl:723
使用问题中定义的 A
和 B
,请注意:
ndims(B)
ndims(A[1,:,:])
returns 2
和 3
分别。所以求和运算失败,因为 B
是一个矩阵,而 A[1,:,:]
是一个 3 维数组。具体来说,A[1,:,:]
就是 1x2x2
。解决方案是 squeeze
第一个维度,如下所示:
B + squeeze(A[1,:,:], 1)
我可以在这里看到混乱的根源。我猜你注意到了:
B[1, :]
returns 键入 Vector
,并且您假设相同的自动压缩原则适用于更高维数组。 github 解决有关此类行为的问题的问题页面是 here。有趣的阅读。
为什么当我 运行 以下代码时 Julia 会抛出错误?
毕竟,A[1,:,:]
在逻辑上是一个二维数组。
如果我没记错的话,类似的代码可以在 MATLAB 中运行。
julia> A = reshape(1:8, 2, 2, 2)
2x2x2 Array{Int64,3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
5 7
6 8
julia> B = reshape(1:4, 2, 2)
2x2 Array{Int64,2}:
1 3
2 4
julia> B + A[1,:,:]
ERROR: dimensions must match
in promote_shape at operators.jl:211
in promote_shape at operators.jl:207
in + at array.jl:723
使用问题中定义的 A
和 B
,请注意:
ndims(B)
ndims(A[1,:,:])
returns 2
和 3
分别。所以求和运算失败,因为 B
是一个矩阵,而 A[1,:,:]
是一个 3 维数组。具体来说,A[1,:,:]
就是 1x2x2
。解决方案是 squeeze
第一个维度,如下所示:
B + squeeze(A[1,:,:], 1)
我可以在这里看到混乱的根源。我猜你注意到了:
B[1, :]
returns 键入 Vector
,并且您假设相同的自动压缩原则适用于更高维数组。 github 解决有关此类行为的问题的问题页面是 here。有趣的阅读。