Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Julia – Reshaping a 4D array into a matrix of matrices

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading