3d array Literal

In C, 3d array literal is written as

int arr[3][3][3]=   
		{
		    {
			{11, 12, 13},
			{14, 15, 16},
			{17, 18, 19}
		    },
		    {
			{21, 22, 23},
			{24, 25, 26},
			{27, 28, 29}
			},
			{
			{31, 32, 33},
			{34, 35, 36},
			{37, 38, 39}
			},
		};

I wonder how to write 3d array literal in Julia and higher dimensional array in general.

I tried below but it produces only 2d array:

a = [
[1 2 3; 4 5 6];
[11 12 13; 14 15 16];
[21 22 23; 24 25 26];
]

6×3 Array{Int64,2}:
1 2 3
4 5 6
11 12 13
14 15 16
21 22 23
24 25 26

1 Like

I don’t think there is syntax for this, see

https://github.com/JuliaLang/julia/pull/33697

Just construct it — eg cat(...; dims = 3).

4 Likes

Or, alternatively, provide a matrix/vector and reshape.

That’s right. I tried permutedims!(reshape(1:8, (2,2,2)), (2,1,3)) and it works well indeed! A bit cumbersome due to column-major vs row-major conversion :slight_smile: It should be really great if syntax for multidimensional array is merged in near future.

TBH, while I agree that it is nice when you need it, it is not something that is used so often that it needs its own specific syntax.

Something like

"Concatenate along an extra first dimension."
function upcat(a::AbstractArray{T,N}, rest...) where {T,N}
    @assert all(ndims.(rest) .== N)
    permutedims(cat(a, rest...; dims = N + 1), (N + 1, ntuple(identity, N)...))
end

A = upcat([1 2 3; 4 5 6],
          [11 12 13; 14 15 16],
          [21 22 23; 24 25 26])

would be more generic and allow nesting to arbitrary dimensions (warning: not well-tested, optimized, etc).

2 Likes

The feature was merged a few years ago for anyone finding this thread. Here is a comment describing it Syntax for multidimensional arrays by BioTurboNick · Pull Request #33697 · JuliaLang/julia · GitHub

example:

julia> [1 2 3
        4 5 6
       ;;;
        7 8 9
        0 1 2]

2×3×2 Array{Int64, 3}:
[:, :, 1] =
 1  2  3
 4  5  6

[:, :, 2] =
 7  8  9
 0  1  2

or

julia> [1 2 3; 4 5 6;;; 7 8 9; 10 11 12]
2×3×2 Array{Int64, 3}:
[:, :, 1] =
 1  2  3
 4  5  6

[:, :, 2] =
  7   8   9
 10  11  12

Note: [1 ;; 2] is treated as [1 ; ; 2] so double column do not work

2 Likes

I’m not sure what you mean by “double column do not work”, but I think showcasing the use of ;; is important to explain why ;;; has three semicolons.

; separates items within a column (along dimension 1), ;; separates columns (along dimension 2), and ;;; separates pages (along dimension 3) etc. So that array can also be written as

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

(the chosen numbers make this look a bit arbitrary, but we could have entered the numbers column by column to begin with and gotten

[1; 2;; 3; 4;; 5; 6;;; # etc

)

3 Likes