Reputation: 1182
I want to initialise a 3-dimensional array in Julia with constant entries. For the 2d case I can use
A = [1 2; 3 4]
Is there a similar short syntax for 3d arrays?
Upvotes: 10
Views: 8148
Reputation: 41
Julia documentation about Multi-dimensional Arrays is a good place to learn more about array creation.
For a 3-dimensional array, you can do the following:
julia> [1; 2;; 3; 4;; 5; 6;;;
7; 8;; 9; 10;; 11; 12]
2×3×2 Array{Int64, 3}:
[:, :, 1] =
1 3 5
2 4 6
[:, :, 2] =
7 9 11
8 10 12
From the documentation, "... ;
and ;;
concatenate in the first and second dimension, using more semicolons extends this same general scheme. The number of semicolons in the separator specifies the particular dimension, so ;;;
concatenates in the third dimension, ;;;;
in the 4th, and so on."
Upvotes: 3
Reputation: 930
It is actually possible to declare a multidimensional array in julia using only list comprehension
julia> a = [x + y + z for x in 1:2, y ∈ 2:3, z = 3:4]
2×2×2 Array{Int64,3}:
[:, :, 1] =
6 7
7 8
[:, :, 2] =
7 8
8 9
julia> size(a)
(2, 2, 2)
julia> ndims(a)
3
Upvotes: 5
Reputation: 1014
One can use either the cat
or the reshape
functions to accomplish the task: (tested with Julia-1.0.0):
julia> cat([1 2; 3 4], [5 6; 7 8], dims=3)
2×2×2 Array{Int64,3}:
[:, :, 1] =
1 2
3 4
[:, :, 2] =
5 6
7 8
For higher Array
dimensions, the cat
calls must be nested: cat(cat(..., dims=3), cat(..., dims=3), dims=4)
.
The reshape
function allows building higher dimension Arrays
"at once", i.e., without nested calls:
julia> reshape([(1:16)...], 2, 2, 2, 2)
2×2×2×2 Array{Int64,4}:
[:, :, 1, 1] =
1 3
2 4
[:, :, 2, 1] =
5 7
6 8
[:, :, 1, 2] =
9 11
10 12
[:, :, 2, 2] =
13 15
14 16
Upvotes: 8
Reputation: 11644
Not at this time, although something like the following isn't too bad
A = zeros(2,2,2)
A[:,:,1] = [1 2; 3 4]
A[:,:,2] = [10 20; 30 40]
Upvotes: 9