Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and initialise 3-dimensional array

Tags:

julia

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?

like image 938
akxlr Avatar asked Aug 29 '14 03:08

akxlr


People also ask

How do you initialize a 3 dimensional array in Java?

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.

How do you initialize a 3d array in C++?

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 .


2 Answers

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]
like image 84
IainDunning Avatar answered Nov 05 '22 05:11

IainDunning


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
like image 29
cnaak Avatar answered Nov 05 '22 07:11

cnaak