Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i create 2d array with list comprehesion?

To make, 2d array with list comprehesion, i write this:

array = [f(i) for in 1:length]

at this, function f returns 1-d list. But at the result as nested array.... How can i create 2d array with list comprehension?

The example of 2d dimension is like this:

julia> A
2×3 Array{Float64,2}:
 0.0194681  0.195811  0.150168
 0.398199   0.544672  0.942663
like image 375
kn05 Avatar asked Dec 30 '22 22:12

kn05


2 Answers

Since your f already returns a vector (I assume you refer to this type when you write "1-d list") then it is not possible to create a matrix using a comprehension (unless you want to write f(i)[j] in the example of Przemyslaw which will be inefficient).

What you should do is:

reduce(hcat, [f(i) for i in 1:len])

to get a matrix whose columns are the values returned by f(i).

like image 190
Bogumił Kamiński Avatar answered Feb 16 '23 11:02

Bogumił Kamiński


Here it is:

julia> [x*y for x in 1:5, y in 1:3]
5×3 Array{Int64,2}:
 1   2   3
 2   4   6
 3   6   9
 4   8  12
 5  10  15
like image 24
Przemyslaw Szufel Avatar answered Feb 16 '23 11:02

Przemyslaw Szufel