Julia: `cat` inconsistency with scalars and arrays

Created on 14 Oct 2020  路  4Comments  路  Source: JuliaLang/julia

I noticed an inconsistency in the behavior of cat when concatenating values with vectors and arrays.

cat(1, [2 3], dims = 1) # vcat of a scalar to a 1脳2 array
#=
2脳2 Array{Int64,2}:
 1  1
 2  3
=#

cat(1, [2;3], dims = 2) # hcat of scalar to a vector
#=
ERROR: DimensionMismatch("mismatch in dimension 1 (expected 1 got 2)")
=#

cat(1, reshape([2;3], (2,1)), dims = 2) # hcat of scalar to a 2脳1 array
#=
ERROR: DimensionMismatch("mismatch in dimension 1 (expected 1 got 2)")
=#

cat(1, [2 3; 4 5], dims = 1)
#=
3脳2 Matrix{Int64}:
 1  1
 2  3
 4  5
=#

cat(1, [2 3; 4 5], dims = 2)
#=
ERROR: DimensionMismatch("mismatch in dimension 1 (expected 1 got 2)")
=#

It appears that, generally speaking, A) cat can concatenate with a scalar when dims is lower than the dimensionality of the array; B) if dims is equal to the dimensionality, it can only concatenate the scalar if the array is extended along only that dimension; and C) if dims is greater than the dimensionality of the array, it always fails.

  • Is case A an intentional feature or unintentional? (It doesn't appear to be documented?)
  • Should the only legal concatenation of a scalar with an array be case B, where the array is only extended in the one dimension being concatenated and all others illegal?
  • Should a scalar always be expanded to fill a 1-length extension of the array along the specified dimension, as in case A?
arrays bug

All 4 comments

#34395

Coming from #34395, I think the following seem like valid uses of cat with scalars and should be preserved:

cat(1, 2, 3, dims = (1, 2, 3)) # [1 0 0; 0 0 0; 0 0 0;;  0 0 0; 0 2 0; 0 0 0;;  0 0 0; 0 0 0; 0 0 3]
cat(1, [2 3], dims = 2) # [1 2 3]
cat(1, reshape([2; 3], (2, 1)), dims = 1) # [1; 2; 3]

Another bugged case: [fill(1); rand(2, 2, 2)] hits some sort of non-terminating loop/recursion.

Edit: it's an infinite loop.

https://github.com/JuliaLang/julia/blob/5b2dffa7ed6950074fc458a01bed05f010ce639f/base/indices.jl#L206

Another bugged case: [fill(1); rand(2, 2, 2)] hits some sort of non-terminating loop/recursion.

Edit: it's an infinite loop.

https://github.com/JuliaLang/julia/blob/5b2dffa7ed6950074fc458a01bed05f010ce639f/base/indices.jl#L206

Looks like an issue with 0-dimensional arrays?

Was this page helpful?
0 / 5 - 0 ratings