Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshaping in julia

If I reshape in python I use this:

import numpy as np

y= np.asarray([1,2,3,4,5,6,7,8])
x=2
z=y.reshape(-1, x)


print(z)

and get this

>>> 
[[1 2]
 [3 4]
 [5 6]
 [7 8]]

How would I get the same thing in julia? I tried:

z = [1,2,3,4,5,6,7,8]
x= 2
a=reshape(z,x,4)

println(a)

and it gave me:

[1 3 5 7
 2 4 6 8]

If I use reshape(z,4,x) it would give

[1 5
 2 6
 3 7
 4 8]

Also is there a way to do reshape without specifying the second dimension like reshape(z,x) or if the secondary dimension is more ambiguous?

like image 578
ccsv Avatar asked Dec 25 '22 02:12

ccsv


1 Answers

I think what you have hit upon is NumPy stores in row-major order and Julia stores arrays in column major order as covered here.

So Julia is doing what numpy would do if you used

z=y.reshape(-1,x,order='F')

what you want is the transpose of your first attempt, which is

z = [1,2,3,4,5,6,7,8]
x= 2
a=reshape(z,x,4)'

println(a)

you want to know if there is something that will compute the 2nd dimension assuming the array is 2 dimensional? Not that I know of. Possibly ArrayViews? Here's a simple function to start

julia> shape2d(x,shape...)=length(shape)!=1?reshape(x,shape...):reshape(x,shape[1],Int64(length(x)/shape[1]))
shape2d (generic function with 1 method)

julia> shape2d(z,x)'
4x2 Array{Int64,2}:
 1  2
 3  4
 5  6
 7  8
like image 85
waTeim Avatar answered Dec 28 '22 14:12

waTeim