It is possible to create matrices from comprehensions directly:
In [4]: [i+j for i=0:1, j=1:2]
Out [4]: 2x2 Array{Int64,2}:
1 2
2 3
Otherwise, in your case:
In [10]: [f()[i] for i=1:2, j = 1:3]
Out [10]: 2x3 Array{Float64,2}:
3.0 3.0 3.0
5.0 5.0 5.0
But that calls `f()` on every loop of your comprehension, so it's probably
best to do something like:
g = f()
In [13]: [g[i] for i=1:2, j=1:3]
Out [13]: 2x3 Array{Any,2}:
3.0 3.0 3.0
5.0 5.0 5.0
On Wed, Aug 13, 2014 at 9:17 PM, Brendan O'Connor <[email protected]>
wrote:
> Hi, I'd like to create a matrix with an array comprehension.
> Specifically, I have a function that returns a 2-length array, like
>
> function f()
> [3.0, 5.0]
> end
>
> And I'd like an Nx2 (or 2xN) matrix from its output. Unfortunately, an
> obvious way of calling it results in:
>
> [f() for i=1:3]
>
> 3-element Array{Array{Float64,1},1}:
> [3.0,5.0]
> [3.0,5.0]
> [3.0,5.0]
>
> Is there a general way to convert Array{Array{float, 1}, 1} into an
> Array{float, 2} ? reshape() and convert() both don't seem to do it. I
> guess hcat() (or vcat()) could do it if it was called with each element in
> the original array as one of its arguments.
>
> I read through the docs page but didn't see anything obvious:
> http://docs.julialang.org/en/release-0.3/manual/arrays/
>
> This is also no better:
>
> [f()' for i=1:3]
>
> 3-element Array{Array{Float64,2},1}:
> 1x2 Array{Float64,2}:
> 3.0 5.0
> 1x2 Array{Float64,2}:
> 3.0 5.0
> 1x2 Array{Float64,2}:
> 3.0 5.0
>
>