Home > OS >  Julia - Reshaping a 4D array into a matrix of matrices
Julia - Reshaping a 4D array into a matrix of matrices

Time:01-25

I want to start from an array like A = zeros( nK , nK , m , m ) and reshape it into an matrix of size (nK,nK) where each element is an mxm matrix.

I have tried the basis reshape function, reshape(A , nK , nK ), but it gives me

DimensionMismatch("new dimensions (nK, nK) must be consistent with array size mxmxnKxnK")

CodePudding user response:

If I understand your problem correctly, I think you can do it this:

julia> x = rand(1:10, 2, 4, 3, 3)
2×4×3×3 Array{Int64, 4}:
[:, :, 1, 1] =
 9  5  4   1
 2  2  2  10

[:, :, 2, 1] =
 8  1  4  9
 9  5  5  8

...

julia> # With copy:

julia> [x[i, j, :, :] for i in axes(x, 1), j in axes(x, 2)]
2×4 Matrix{Matrix{Int64}}:
 [9 5 4; 8 2 6; 5 7 5]  [5 8 5; 1 6 1; 1 5 5]   [4 10 4; 4 3 10; 4 7 10]  [1 10 5; 9 2 5; 7 1 10]
 [2 7 1; 9 5 3; 7 1 7]  [2 3 9; 5 7 10; 4 1 4]  [2 1 2; 5 1 1; 1 2 4]     [10 1 3; 8 3 8; 9 10 2]

julia> # With views:

julia> [view(x, i, j, :, :) for i in axes(x, 1), j in axes(x, 2)]
2×4 Matrix{SubArray{Int64, 2, Array{Int64, 4}, Tuple{Int64, Int64, Base.Slice{Base.OneTo{Int64}}, Base.Slice{Base.OneTo{Int64}}}, true}}:
 [9 5 4; 8 2 6; 5 7 5]  [5 8 5; 1 6 1; 1 5 5]   [4 10 4; 4 3 10; 4 7 10]  [1 10 5; 9 2 5; 7 1 10]
 [2 7 1; 9 5 3; 7 1 7]  [2 3 9; 5 7 10; 4 1 4]  [2 1 2; 5 1 1; 1 2 4]     [10 1 3; 8 3 8; 9 10 2]

I hope it helps you.

  • Related