Sijun
February 29, 2020, 12:03am
1
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
.
Sijun
February 29, 2020, 9:43am
4
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 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