How to reshape() using an array instead of a tuple / Alt: How to convert an array into a tuple

Hello,

I have something like this:

data = [ ... long array of numbers ... ]
dims = [1024,256,128]  # (for example)

I want to reshape the data and ideally I would like to do this:

reshape(data,dims)

The problem I have is that reshape() wants the dimensions as a tuple and dims is an array (note that dims is unknown at the start of the program). So I have to reshape() to allow me to use an array, or convert the array into a tuple. For example, I could do this:

reshape(data,ntuple(j -> dims[j],length(dims)))

Technically this works. But I imagine that there has to be a cleaner way to reshape an array. I cannot imagine that anyone who designed Julia intended for people to run this just to reshape an array. So I’m wondering if there is an alternate recommended way to do what I want to do.

Cheers,
Daniel

You can just say Tuple(dims).

BTW the reason reshape wants a tuple while e.g. sum accepts a vector is that the length of dims is then part of the type, so that the type of the output array (e.g. Array{Int,3} for your dims) can be determined from the type of the inputs.

1 Like

Thanks! That’s exactly what I need. I’d swear I tried that. I wonder what I did to get it wrong… Oh. I see what I did:

Tuple(3,4) # wrong
tuple(dims) # wrong
Tuple(dims) # yay!

Yea it’s a bit confusing. tuple([1,2,3]...) == Tuple([1,2,3]) == ([1,2,3]...,) == tuple(1,2,3) == (1,2,3), maybe that’s the complete list?

Wow. What does the “…” mean?

julia> tuple([1,2,3])
([1, 2, 3],)

julia> tuple([1,2,3]...)
(1, 2, 3)

julia> [1,2,3]...
ERROR: syntax: "..." expression outside call

It’s called splatting. Here, it basically “unpacks” the array so that instead of tuple([1, 2, 3]) you have tuple(1, 2, 3) which gives the desired result: (1, 2, 3).
You can do the same if you have a function that takes multiple arguments but you have an array/tuple/named tuple with them in it: f(a, b, c) = a * b + c and then f((1.0, 4.0, 5.3)...)