Is there a function to flatten a multidimensional array?

7,911 views
Skip to first unread message

Johan Sigfrids

unread,
Dec 5, 2013, 7:24:57 PM12/5/13
to julia...@googlegroups.com
Does julia have a function to flatten a multidimensional array into a single dimensional one? I.e. something like
>flatten([1 4; 2 5; 3 6])
6-element Array{Int64,1}:
 1
 
2
 
3
 
4
 
5
 
6



Blake Johnson

unread,
Dec 5, 2013, 8:26:13 PM12/5/13
to julia...@googlegroups.com
Try vec(a). Or simply a[:]

Johan Sigfrids

unread,
Dec 6, 2013, 6:27:21 AM12/6/13
to julia...@googlegroups.com
Thanks, just what I was looking for.

Jacob Quinn

unread,
Dec 6, 2013, 6:42:29 AM12/6/13
to julia...@googlegroups.com
Also note the more general reshape function: http://docs.julialang.org/en/latest/stdlib/base/#Base.reshape

Example:

In  [6]: t = [1 4; 2 5; 3 6]

Out [6]: 3x2 Array{Int64,2}:
 1  4
 2  5
 3  6

In  [7]: reshape(t,1,6)

Out [7]: 1x6 Array{Int64,2}:
 1  2  3  4  5  6

In  [8]: reshape(t,6,1)

Out [8]: 6x1 Array{Int64,2}:
 1
 2
 3
 4
 5
 6

Tim Holy

unread,
Dec 6, 2013, 8:20:30 AM12/6/13
to julia...@googlegroups.com
flat = A[:]

Anthony Voutas

unread,
Mar 28, 2015, 8:39:18 PM3/28/15
to julia...@googlegroups.com
None of the above are working for me.

s = "string"
arr = [s,s,s,s]
transform = (x -> [x, x*"d"])
chunky = map(transform, arr)

# chunky is now 4 by 2
vec(chunky) # no change
chunky[:] # no change
reshape(chunky, 1, 8) # fails with dimension mismatch

I'm guessing something has changed with Julia since the last comment here but I can't seem to find an updated answer anywhere.

Tim Holy

unread,
Mar 29, 2015, 6:40:43 AM3/29/15
to julia...@googlegroups.com
It's not a 4-by-2 array, it's a 4-vector of 2-vectors. If you want to create a
4-by-2 array, use

chunky = [a*b for a in arr, b in ("", "d")]

--Tim
Reply all
Reply to author
Forward
0 new messages