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?
We can initialize a 3d array similar to the 2d array. For example, // test is a 3d array int[][][] test = { { {1, -2, 3}, {2, 3, 4} }, { {-4, -5, 6, 9}, {1}, {2, 3} } }; Basically, a 3d array is an array of 2d arrays.
Initialization of three-dimensional array A better way to initialize this array is: int test[2][3][4] = { { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} } }; Notice the dimensions of this three-dimensional array. The second dimension has the value 3 .
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With