Raghvender
Raghvender

Reputation: 83

Is there a way in Julia to reshape and fill the elements in row-major ways?

I want to use Julia to reshape an array like this:

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

into this:

   a = 4*3*2 Array
 
   [[[1,  2,  3] 
     [4,  5,  6]
     [7,  8,  9]
     [10, 11, 12]
 
    [[13, 14, 15]
     [16, 17, 18]
     [19, 20, 21]
     [22, 23, 24]]

However, I don't want to use specifically a "for loop" to do so, any inbuilt function would be ideal for me such as reshape option. Currently, the problem I am facing with the reshape option in Julia is that it fills the elements column-wise.

Upvotes: 4

Views: 788

Answers (1)

Sundar R
Sundar R

Reputation: 14705

You can do a permutedims on the reshape result like this:



julia> permutedims(reshape(1:24, 3, 4, 2), (2, 1, 3))
4×3×2 Array{Int64, 3}:
[:, :, 1] =
  1   2   3
  4   5   6
  7   8   9
 10  11  12

[:, :, 2] =
 13  14  15
 16  17  18
 19  20  21
 22  23  24


Two things to keep in mind:

  • The dimension sizes (dims) you pass to reshape should be changed to match where the dimension eventually will go after the permutedims (4, 3, 2 becomes 3, 4, 2 here).
  • reshape usually doesn't do a copy, instead returns a different view of the original array itself - so if you modify a reshape result, it would modify a as well. If you want that behaviour, instead of permutedims(...), use PermutedDimsArray(...).

Upvotes: 5

Related Questions