What's the best way to convert from Array{Any} to, say, Array{Int64}

1,389 views
Skip to first unread message

Marcos Sainz

unread,
Jul 10, 2013, 9:29:03 PM7/10/13
to julia...@googlegroups.com
Besides the obvious looping answer, I'm using reduce as shown below when performance isn't key,
but is there are a more natural convert built into the API?


julia> arr = {[1,2] [2,4] [3,4]}
1x3 Any Array:
 [1,2]  [2,4]  [3,4]

julia> reduce(hcat, arr)
2x3 Int64 Array:
 1  2  3
 2  4  4

Marcos Sainz

unread,
Jul 10, 2013, 9:45:07 PM7/10/13
to julia...@googlegroups.com
And also, what's the best way to convert the reverse way.
Loops aside, I've got:

julia> reduce(hcat, Array{Any,1}, [1,2,3])
1x4 Any Array:
 Array{Any,1}  1  2  3 

Marcos Sainz

unread,
Jul 10, 2013, 10:36:40 PM7/10/13
to julia...@googlegroups.com
Oops, never mind for the reverse case:
julia> Any[1,2,3]
3-element Any Array:
 1
 2
 3

Terry Seaward

unread,
Jul 10, 2013, 10:55:46 PM7/10/13
to julia...@googlegroups.com
Hi Marcos, would something like this work?

 convert(Array{Int64}, Any[1 2 3; 4 5 6])

Marcos Sainz

unread,
Jul 10, 2013, 11:00:21 PM7/10/13
to julia...@googlegroups.com
Yes! Thank you Terry. 

Marcos Sainz

unread,
Jul 15, 2013, 10:29:01 PM7/15/13
to julia...@googlegroups.com
Related to the above:

What is the preferred way in julia to convert Array{Any} which is really an Array{Array{Float64}} into a Matrix{Float64}. For example:

julia> a
7-element Any Array:
 [1.0,1.0]
 [2.0,3.0]
 [4.0,7.0]
 [5.0,4.0]
 [7.0,2.0]
 [8.0,4.0]
 [9.0,6.0]

julia> reduce(hcat, a)
2x7 Float64 Array:
 1.0  2.0  4.0  5.0  7.0  8.0  9.0
 1.0  3.0  7.0  4.0  2.0  4.0  6.0

 Any better (i.e. more performant or idiomatic) way?

(sorry that I wasn't able to generalize the above answer to solve this case)

Thank you,

Marcos

Simon Kornblith

unread,
Jul 15, 2013, 10:38:42 PM7/15/13
to julia...@googlegroups.com
I think hcat(a...) should work for this.

Marcos Sainz

unread,
Jul 15, 2013, 10:42:22 PM7/15/13
to julia...@googlegroups.com
Thank you Simon. I can now stop abusing 'reduce'. 
How about to go in the other direction, Matrix{Float64} into a cell array of its rows (or columns)? What would be the preferred way?

Simon Kornblith

unread,
Jul 16, 2013, 2:07:49 AM7/16/13
to julia...@googlegroups.com
You should first consider if you need to convert the rows/columns of a matrix into a cell array, since it's rarely the most efficient way of doing things. If there's no better way to do what you want to do, you could use array comprehension:

{a[:, i] for i = 1:size(a, 2)} # cols
{a[i, :][:] for i = 1:size(a, 1)} # rows

or mapslices:

mapslices(x->{x}, a, 1)[:] # cols
mapslices(x->{x}, a, 2)[:] # rows

(The [:] above converts 2D row/column vectors into 1D column vectors. Depending on your application, you may not want/need this.)
Reply all
Reply to author
Forward
0 new messages